Converting string in python to date format - python

I'm having trouble converting a string to data format. I'm using the time module to convert a string to the YYYY-MM-DD format. The code below is what I've tried but I get the following error.
sre_constants.error: redefinition of group name 'Y' as group 5; was group 3
Here is the code
import time
review_date = "April 18, 2018"
review_date = time.strptime(review_date, '%m %d %Y %I:%Y%m%d')

Firstly, the error is because you're using %Y, %m, and %d twice in your time.strptime() call.
Secondly, you're using the wrong format. The format you pass to strptime() has to match the format of the date / time string you pass, which in this case is: %B %d, %Y.
This is a good reference on the different format types.

I normally use datetime for this:
from datetime import datetime
review_date = "April 18, 2018"
review_date = datetime.strptime(review_date, '%B %d, %Y').strftime('%Y-%m-%d')
This code returns review_date = '2018-04-18'. See https://docs.python.org/3/library/datetime.html
The date format for April is %B. strptime() converts to a datetime object, .strftime() converts the datetime object to a string.

time.strptime() is for parsing strings into date/time structures. It takes two arguments, the string to be parsed and another string describing the format of the string to be parsed.
Try this:
time.strptime("April 18, 2018", "%B %d, %Y")
... and notice that "%B %d, %Y" is:
Full locale name of the month ("April")
[Space]
Date of the month (18)
[Comma]
[Space]
Four digit year (2018)
The format string specification that you provided bears no resemblance to the formatting of your date string.
These "magic" formatting codes are enumerated in the documentation for time.strftime()

review_date = time.strptime(review_date, '%B %d, %Y')

import time
review_date = "April 18, 2018"
review_date = time.strptime(review_date, '%B %d, %Y')
That's what you should have

Related

format 01-01-16 7:43 string to datetime

I have the following strings that I'd like to convert to datetime objects:
'01-01-16 7:43'
'01-01-16 3:24'
However, when I try to use strptime it always results in a does not match format error.
Pandas to_datetime function nicely handles the automatic conversion, but I'd like to solve it with the datetime library as well.
format_ = '%m-%d-%Y %H:%M'
my_date = datetime.strptime("01-01-16 4:51", format_)
ValueError: time data '01-01-16 4:51' does not match format '%m-%d-%Y %H:%M'
as i see your date time string '01-01-16 7:43'
its a 2-digit year not 4-digit year
that in order to parse through a 2-digit year, e.g. '16' rather than '2016', a %y is required instead of a %Y.
you can do that like this
from datetime import datetime
datetime_str = '01-01-16 7:43'
datetime_object = datetime.strptime(datetime_str, '%m-%d-%y %H:%M')
print(type(datetime_object))
print(datetime_object)
give you output 2016-01-01 07:43:00
First of all, if you want to match 2016 you should write %Y while for 16 you should write %y.
That means you should write:
format_ = '%m-%d-%y %H:%M'
Check this link for all format codes.

Python Convert unusual date string to datetime format

I have date string like this:
Saturday, 30 Nov, 2013
So it is like Day_Name, Day, Month_Name_3_Letters, Year.
I wonder what is the best way to convert it to datetime format using python?
I using like this:
datetime.strptime((row[7].split(',')[1] + row[7].split(',')[2]).replace(' ',''), "%d%b%Y").strftime("%Y-%m-%d")
Use strptime:
import datetime as dt
s = 'Saturday, 30 Nov, 2013'
d = dt.datetime.strptime(s,'%A, %d %b, %Y')
Result:
>>> d
datetime.datetime(2013, 11, 30, 0, 0)
As you'll see from the reference:
%A Weekday as locale’s full name.
%d Day of the month as a zero-padded decimal number.
%b Month as locale’s abbreviated name.
%Y Year with century as a decimal number.
You can use strptime function and initialize it as the following:
from datetime import datetime
datetime_object = datetime.strptime('Saturday, 30 Nov, 2013', '%A, %d %b, %Y')
print datetime_object
Conversely, the datetime.strptime() class method creates a datetime
object from a string representing a date and time and a corresponding
format string. datetime
In order to see how to use the formats and when, you can see strftime formats
Why don't you use dateutil's parse ?
from dateutil import parser
parser.parse('Saturday, 30 Nov, 2013')
datetime.datetime(2013, 11, 30, 0, 0)
from datetime import datetime
st='Saturday, 30 Nov, 2013'
print datetime.strptime(st,'%A, %d %b, %Y')
OUTPUT
2013-11-30 00:00:00
See strptime() at Tutorials point

Python date conversion?

I'm currently trying to convert a file format into a slightly different style to allow easier importing into a program however I can't quite get my head around how to convert datetime strings between formats. The original I have is the following:
2016-12-15 17:26:45
However the required format for the date time is:
Thu Dec 15 17:19:03 2016
Does anyone know if there is an easy way to convert between these? These values are always in the same place and format so it doesn't need to be too dynamic so to speak outside of recognising what a certain day of the month is (if that can be done at all?)
Update - The conversion has worked for 1 date but not the other weirdly :/ The code to grab the two dates is the following:
startDate=startDate.replace("Started : ","")
startDate=startDate.replace(" (ISO format YYYY-MM-DD HH:MM:SS)","")
startDate=startDate.strip()
startDt = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S')
startDt=startDt.strftime('%a %b %d %H:%M:%S %Y ')
print (startDt)
This part works as inteded and outputs the required format:
"2016-12-15 17:26:45
Thu Dec 15 17:26:45 2016"
The end date part is a bit "ham fisted" so to speak and I'm sure there are better ways to do the re.sub search just to do anything in brackets but I'll edit that later.
endDate=endDate.replace("Ended : ","")
endDate=endDate.strip()
endDate = re.sub("\(.*?\)", "", endDate)
endDate.strip()
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
endDt=endDt.strftime('%a %b %d %H:%M:%S %Y ')
print (endDt)
This part however despite the outputs being an identical format
"2016-12-15 17:26:45
2016-12-15 21:22:11"
produces the following error:
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
File "C:\Python27\lib\_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
from datetime import datetime
dt = datetime.strptime('2016-06-01 1:33:45', '%Y-%m-%d %H:%M:%S')
dt.strftime('%a %b %d %H:%M:%S %Y ')
>>> 'Wed Jun 01 01:33:45 2016'
It's a pretty easy task with the Datetime module.
As it's been pointed out, checking the docs will get you a lot of useful info, starting from the directives to feed to the strptime and strftime (respectively, parse and format time) functions which you'll need here.
A working example for you case would be:
from datetime import datetime
myDateString = '2016-12-15 17:26:45'
myDateObj = datetime.strptime(myDateString, '%Y-%m-%d %H:%M:%S')
myDateFormat = myDateObj.strftime('%a %b %d %H:%M:%S %Y')
Check out this section of the docs to have a better understanding of the formatting placeholders.
You can use the datetime module:
from datetime import datetime
string = '2016-12-15 17:26:45'
date = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
date2 = date.strftime("%a %b %d %H:%M:%S %Z %Y")
print(date2)
Output:
Thu Dec 15 17:26:45 2016

Converting String to Date Format in Python

I have the following date I need to convert:
Wed, 09 Jul 2014 12:22:17 +0000
This is currently stored as a String. I wrote this code to convert it to the date format I want (the String above is passed as an argument to the covertDate function):
def convertDate(dictValue):
date_string = dictValue
format_string = '%a, %d %b %Y %H:%M:%S %z'
date_object = datetime.datetime.strptime(date_string, format_string)
date_correct_form = date_object.strftime("%Y-%m-%d")
print(type(date_correct_form))
print(date_correct_form)
return date_correct_form
The output is as follows:
<class 'str'>
2014-10-30
I get the format that I want, but it still isn't recognized as a date.
How can I make it so?
You are returning date_correct_form, which is the result of strftime:
Return a string representing the date, controlled by an explicit format string.
(emphasis mine)
If you want the datetime object, return date_object. If you need both, you can return both:
return date_correct_form, date_object
You can call it like so:
date_string, date_obj = convertDate(dictValue)
You now have the already formatted string in date_string, and if you still need to do logic against the datetime object, that is in date_obj
You can use easy_date to make it easy:
import date_converter
converted_date = date_converter.string_to_date(date_string, '%a, %d %b %Y %H:%M:%S %z')

OpenERP 6.1 datetime formatting

Why does
o.create_order.strftime("%d %B %Y")
returns nothing when
time.strftime("%d %B %Y")
returns the date "10 february 2013"???
o.create_order is a timestamp according to postgresql.
It contains "30/11/2012 09:38:34" as seen on the openErp sale order - Other information tab.
It is stored as "2012-11-30 08:38:34.272" when querying the database.
So I would expect to see "30 November 2012" but get nothing instead.
Am I misinterpreting the syntax?
I tested this from python 3.3:
>>> d1=datetime.datetime.today()
>>> print(d1.strftime("%d %B %Y"))
10 february 2013
How do I get it to work in OpenOffice Writer?
And by the way how do I get "February" instead of "february"?
Because o.create_order returns a string and not a datetime object, even if, internally, the database column is a timestamp. The OpenERP ORM returns a string in ISO 8601 format.
You need to use the formatLang method which is available in RML reports or create a datetime object using the datetime python module.
Try this:
datetime.strftime('%d %B %Y', o.create_order')
It is because o.create_order returns a string. So first you have to convert your string date into datetime format and then again you can convert it into any format you want as a string.
Try this:
#Converts string into datetime format.
dt1 = datetime.strptime(o.create_order,"%Y-%m-%d %H:%M:%S")
#Converts datetime into your given formate and returns string.
dt2 = datetime.strftime(dt,"%d %B %Y")
Hope this will solve your problem.

Categories