Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why %z is not supported by python's strptime?

>>> datetime.strptime('2014-02-13 11:55:00 -0800', '%Y-%m-%d %H:%M:%S %z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'

I understand that it's not supported, but don't know why. Seems it's not hard to support that. And 'Offset from UTC' is not as ambiguous as timezone abbreviation.

like image 880
wanghq Avatar asked Dec 22 '25 04:12

wanghq


1 Answers

Until Python 3.2, Python's datetime module had no timezone() object. It supported 3rd-party libraries providing timezones by providing a datetime.tzinfo() abstract base class, but no timezone object was included. Without a timezone object, no support for parsing timezone offsets either.

As of Python 3.2, z is supported, because that version (and up) added a datetime.timezone() type:

>>> import datetime
>>> datetime.datetime.strptime('2014-02-13 11:55:00 -0800', '%Y-%m-%d %H:%M:%S %z')
datetime.datetime(2014, 2, 13, 11, 55, tzinfo=datetime.timezone(datetime.timedelta(-1, 57600)))
>>> _.tzinfo
datetime.timezone(datetime.timedelta(-1, 57600))
like image 177
Martijn Pieters Avatar answered Dec 23 '25 21:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!