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
Related
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
I'm trying to convert string date object to date object in python.
I did this so far
old_date = '01 April 1986'
new_date = datetime.strptime(old_date,'%d %M %Y')
print new_date
But I get the following error.
ValueError: time data '01 April 1986' does not match format '%d %M %Y'
Any guess?
%M parses minutes, a numeric value, not a month. Your date specifies the month as 'April', so use %B to parse a named month:
>>> from datetime import datetime
>>> old_date = '01 April 1986'
>>> datetime.strptime(old_date,'%d %B %Y')
datetime.datetime(1986, 4, 1, 0, 0)
From the strftime() and strptime() Behavior section:
%B
Month as locale’s full name.
January, February, ..., December (en_US);
Januar, Februar, ..., Dezember (de_DE)
%M
Minute as a zero-padded decimal number.
00, 01, ..., 59
You can first guess the type of date format the string is using and then convert to the same system recognised date format.
I wrote a simple date_tools utilities that you can find here at [https://github.com/henin/date_tools/]
Installation: pip install date-tools
Usage:
from date_tools import date_guesser
from datetime import datetime
old_date = '01 April 1986'
date_format = date_guesser.guess_date_format(old_date)
new_date = datetime.strptime(old_date, date_format)
print(new_date)
I have found a question at this link that almost answers what I need but not quite. What I need to know, how using this method could I convert a string of the format u'Saturday, Feb 27 2016' into a Python date variable in the format 27/02/2016?
Thanks
You have to first remove the weekday name (it's not much use anyway) and parse the rest:
datetime.datetime.strptime('Saturday, Feb 27 2016'.split(', ', 1)[1], '%b %d %Y').date()
Alternatively, use dateutil:
dateutil.parser.parse('Saturday, Feb 27 2016').date()
EDIT
My mistake, you don't need to remove the Weekday (I'd missed it in the list of options):
datetime.datetime.strptime('Saturday, Feb 27 2016', '%A, %b %d %Y').date()
You don't have to remove anything, you can parse it as is and use strftime to get the format you want:
from datetime import datetime
s = u'Saturday, Feb 27 2016'
dt = datetime.strptime(s,"%A, %b %d %Y")
print(dt)
print(dt.strftime("%d/%m/%Y"))
2016-02-27 00:00:00
27/02/2016
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%d Day of the month as a decimal number [01,31].
%Y Year with century as a decimal number.
The full listing of directives are here
I'm trying to convert a string given in "DD MM YYYY" format into a datetime object. Here's the code for the same:
from datetime import date, timedelta
s = "23 July 2001"
d = datetime.datetime.strptime(s, "%d %m %Y")
However, I get the following error:
ValueError: time data '23 July 2001' does not match format '%d %m %Y'
What's wrong ? Isn't the format specified in the string the same as that specified by "%d %m %Y" ?
%m means "Month as a zero-padded decimal number."
Your month is July so you should use %B, which is "Month as locale’s full name."
Reference: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Like behzad.nouri said, Use d = datetime.datetime.strptime(s, "%d %B %Y").
Or make s = '23 07 2001' and d = datetime.datetime.strptime(s, "%d %m %Y")
I have dates in the current string format: 'Tue Feb 19 00:09:28 +1100 2013'
I'm trying to figure out how many days have passed between the date in the string and the present date.
I've been able to convert the string into a date.
import time
day = time.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
Use the datetime module instead:
import datetime
day = datetime.datetime.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
delta = day - datetime.datetime.now()
print delta.days
Subtracting two datetime.datetime values returns a datetime.timedelta object, which has a days attribute.
Your strings do contain a timezone offset, and you hardcoded it to match; if the value varies you'll have to use a parser that can handle the offset. The python-dateutil package includes both an excellent parser and the timezone support to handle this:
>>> from dateutil import parser
>>> parser.parse('Tue Feb 19 00:09:28 +1100 2013')
datetime.datetime(2013, 2, 19, 0, 9, 28, tzinfo=tzoffset(None, 39600))
Note that because this result includes the timezone, you now need to use timezone-aware datetime objects when using date arithmetic:
>>> from dateutil import tz
>>> import datetime
>>> utcnow = datetime.datetime.now(tz.tzutc())
>>> then = parser.parse('Tue Feb 19 00:09:28 +1100 2013')
>>> utcnow - then
datetime.timedelta(31, 12087, 617740)
>>> (utcnow - then).days
31
I created a utcnow variable in the above example based of the UTC timezone before calculating how long ago the parsed date was.