In Python how do I convert a datetime object like datetime.datetime(2010, 12, 18, 22, 21, 45, 277000) to something like "Sun Dec 18 2010 22:21:45 GMT+0000 (UTC)"?
You can use strftime for this purpose. Read more here.
Not sure about utc offset, but seems that you can use something like this:
import datetime
d = datetime.datetime(2010, 12, 18, 22, 21, 45, 277000)
d.strftime("%a %b %d %Y %H:%M:%S %z")
>>> Sat Dec 18 2010 22:21:45
Where using the link above:
%a - Locale’s abbreviated weekday name
%b - Locale’s abbreviated month name
%d - Day of the month as a decimal number [01,31]
%H - Hour (24-hour clock) as a decimal number [00,23]
%M - Minute as a decimal number [00,59]
%S - Second as a decimal number [00,61]
%z - UTC offset in the form +HHMM or -HHMM (empty string if the the
object is naive)
Related
I am trying to match a specific datetime format from a string but I am receiving a ValueError and I am not sure why. I am using the following format:
t = datetime.datetime.strptime(t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
which is an attempt to match the following string:
Nov 19, 2017 20:09:14.071360000 Eastern Standard Time
Can anyone see why these do not match?
From the docs we can see that %f expects:
Microsecond as a decimal number, zero-padded on the left.
The problem with your string is that you have a number that's zero-padded on the right.
Here is one way to fix your issue:
new_t = t.partition(" Eastern Standard Time")[0].rstrip('0') + ' Eastern Standard Time'
print(new_t)
#Nov 19, 2017 20:09:14.07136 Eastern Standard Time
t2 = datetime.datetime.strptime(new_t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
print(t2)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)
As noted by pault and the documentation, the issue is that the %f directive is essentially limited to 6 decimal places for your microseconds. While their solution works fine for your string, you might have an issue if your string is something like
'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'
Because calling rstrip('0') in that case would not cut the microseconds to the proper length. You could otherwise do the same with regex:
import re
import datetime
date_string = 'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'
# use a regex to strip the microseconds to 6 decimal places:
new_date_string = ''.join(re.findall(r'(.*\.\d{6})\d+(.*)', date_string)[0])
print(new_date_string)
#'Nov 19, 2017 20:09:14.071360 Eastern Standard Time'
t = datetime.datetime.strptime(new_date_string,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
print(t)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)
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
I was trying to convert a string to a datetime object.
The string I got from a news feed is in the following format:
"Thu, 16 Oct 2014 01:16:17 EDT"
I tried using datetime.strptime() to convert it.
i.e.,
datetime.strptime('Thu, 16 Oct 2014 01:16:17 EDT','%a, %d %b %Y %H:%M:%S %Z')
And got the following error:
Traceback (most recent call last):
File "", line 1, in
datetime.strptime('Thu, 16 Oct 2014 01:16:17 EDT','%a, %d %b %Y %H:%M:%S %Z')
File "C:\Anaconda\lib_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Thu, 16 Oct 2014 01:16:17 EDT' does not match
format '%a, %d %b %Y %H:%M:%S %Z'
However, if I tried the string without "EDT", it worked.
i.e.,
datetime.strptime('Thu, 16 Oct 2014 01:16:17','%a, %d %b %Y %H:%M:%S')
Does anyone know how to parse that "EDT" part?
To parse the date in RFC 2822 format, you could use email package:
from datetime import datetime, timedelta
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz("Thu, 16 Oct 2014 01:16:17 EDT"))
# -> 1413436577
utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
# -> datetime.datetime(2014, 10, 16, 5, 16, 17)
Note: parsedate_tz() assumes that EDT corresponds to -0400 UTC offset but it might be incorrect in Australia where EDT is +1100 (AEDT is used by pytz in this case) i.e., a timezone abbreviation may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?
Related Python bug: %Z in strptime doesn't match EST and others.
If your computer uses POSIX timestamps (likely), and you are sure the input date is within an acceptable range for your system (not too far into the future/past), and you don't need to preserve the microsecond precision then you could use datetime.utcfromtimestamp:
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz("Thu, 16 Oct 2014 01:16:17 EDT"))
# -> 1413436577
utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2014, 10, 16, 5, 16, 17)
The email.utils.parsedate_tz() solution is good for 3-letter timezones but it does not work for 4 letters such as AEDT or CEST. If you need a mix, the answer under Parsing date/time string with timezone abbreviated name in Python? works for both with the most commonly used time zones.
I'm trying to parse the following string into a valid datetime format:
Wed, 10 Sep 2014 11:20:58 +0000
for which I use this Python code:
dtObject = datetime.strptime(e[attr], '%a, %d %b %Y %H:%M:%S %z')
Unfortunately I get an error saying:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _str
ptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
According to the strptime() docs, %z should be totally correct for UTC offset in the form +HHMM or -HHMM.
Does anybody know what I'm doing wrong here? All tips are welcome
It looks as if strptime doesn't always support %z (see this answer)
Instead of strptime, you can use dateutil.parser and it works fine:
>>> import dateutil.parser
>>> s='Wed, 10 Sep 2014 11:20:58 +0000' #UTC
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzutc())
>>> s='Wed, 10 Sep 2014 11:20:58 +0100' #ANOTHER TZ
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzoffset(None, 3600))
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.