Why doesn't my Python code accept %z as a DateTime directive? - python

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))

Related

Correct format for converting french date from string to datetime?

I'm trying to convert strings to date, but it's not working for some dates in french. Like in the example below :
myDate = datetime.strptime(dateInStringFormat, "%A %d %B %Y %H:%M:%S")
Result with the error : time data '"jeudi 8 septembre 2022 13:51:13"' does not match format '%A %d %B %Y %H:%M:%S'.
I've tried a lot a variations in the format I can't make it work, anyone know how to do this please ?
try:
import locale
import datetime
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
dateInStringFormat = "jeudi 8 septembre 2022 13:51:13"
myDate = datetime.datetime.strptime(dateInStringFormat, "%A %d %B %Y %H:%M:%S")
print(myDate)
# 2022-09-08 13:51:13
myDate
# datetime.datetime(2022, 9, 8, 13, 51, 13)
I had the same problem once and found a module called dateparser to do that:
import dateparser
d = dateparser.parse("jeudi 8 septembre 2022 13:51:13")
d is now
datetime.datetime(2022, 9, 8, 13, 51, 13)

datetime to date format in python

I Have a value of
datetime.datetime(2015, 1, 28, 13, 53, 36)
and I want it to be printed as string as
Wednesday, January 28, 2015 13:53:36
I tried to
import datetime
x = datetime.datetime(2015, 1, 28, 13, 53, 36)
z = strptime(str(x), '%A, %B %d, %Y %H:%M:%S')
but got:
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
z = strptime(str(x), '%A, %B %d, %Y %H:%M:%S')
NameError: name 'strptime' is not defined
does anyone have an idea about this?
Given your import - the correct form of accessing strptime is datetime.datetime.strptime (parsing a string to a date) - but it doesn't look like you want that, instead you're after datetime.datetime.strftime (formats a date to a string).
Ultimately though, Python's datetime object has custom string formatting which can be accessed via str.format and will save a bit of typing, eg:
>>> dt = datetime.datetime(2015, 1, 28, 13, 53, 36)
>>> format(dt, '%A, %B %d, %Y %H:%M:%S')
'Wednesday, January 28, 2015 13:53:36'
Use the date method:
datetime.datetime.date()
You should use datetime.datetime.strptime:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)

Python : Converting string to datetime [duplicate]

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.

Parsing time string in Python

I have a date time string that I don't know how to parse it in Python.
The string is like this:
Tue May 08 15:14:45 +0800 2012
I tried
datetime.strptime("Tue May 08 15:14:45 +0800 2012","%a %b %d %H:%M:%S %z %Y")
but Python raises
'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'
According to Python doc:
%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).
What is the right format to parse this time string?
datetime.datetime.strptime has problems with timezone parsing. Have a look at the dateutil package:
>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))
Your best bet is to have a look at strptime()
Something along the lines of
>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)
Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.
The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.
Hope that helps
Mark
PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ )
in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.
Here's a stdlib solution that supports a variable utc offset in the input time string:
>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)
It has discussed many times in SO. In short, "%z" is not supported because platform not support it.
My solution is a new one, just skip the time zone.:
datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")
In [117]: datetime.datetime.strptime?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in method strptime of type object at 0x9a2520>
Namespace: Interactive
Docstring:
string, format -> new datetime parsed from a string (like time.strptime()).

Converting string with UTC offset to a datetime object [duplicate]

This question already has answers here:
Parsing date with timezone from an email?
(8 answers)
Closed 8 years ago.
Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object?
After doing some reading I feel like this should work, but it doesn't...
>>> from datetime import datetime
>>>
>>> str = 'Fri, 09 Apr 2010 14:10:50 +0000'
>>> fmt = '%a, %d %b %Y %H:%M:%S %z'
>>> datetime.strptime(str, fmt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
It should be noted that this works without a problem:
>>> from datetime import datetime
>>>
>>> str = 'Fri, 09 Apr 2010 14:10:50'
>>> fmt = '%a, %d %b %Y %H:%M:%S'
>>> datetime.strptime(str, fmt)
datetime.datetime(2010, 4, 9, 14, 10, 50)
But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way.
It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.
Note: from Python 3.2 onwards it will always work.

Categories