python convert datetime formatted string to second

2019-06-18 08:14发布

问题:

I am trying to decode a date string to epoch but I have difficulties getting the timezone. This is the last modified date from Amazon S3 keys.

time.strptime(key.last_modified, '%Y-%m-%dT%H:%M:%S.%Z')

ValueError: time data u'2013-10-20T00:41:32.000Z' 
            does not match format '%Y-%m-%dT%H:%M:%S.%Z'

If I get rid of the timezone (.000Z) it works, but I need the timezone as well.

回答1:

The .000Z is not recognized as a timezone offset. In fact, you have milliseconds and a timezone (Z is UTC), and officially, time.strptime() parser cannot handle milliseconds. On some platforms %f will parse the microsecond portion, then discard the information.

The datetime.datetime.strptime() class method, however, can, but not the timezone, however; parse the Z as a literal and it works:

from datetime import datetime

datetime.strptime(key.last_modified, '%Y-%m-%dT%H:%M:%S.%fZ')

Demo:

>>> from datetime import datetime
>>> import time
>>> example = u'2013-10-20T00:41:32.000Z'
>>> datetime.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2013, 10, 20, 0, 41, 32)
>>> time.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')
time.struct_time(tm_year=2013, tm_mon=10, tm_mday=20, tm_hour=0, tm_min=41, tm_sec=32, tm_wday=6, tm_yday=293, tm_isdst=-1)

Note that on my Mac OS X laptop, %f works for time.strptime(); it is not guaranteed to work everywhere, however.

Converting a datetime.datetime() object to a time tuple can be done with the datetime.timetuple() method.



回答2:

2013-10-20T00:41:32.000Z

In this string, 32.000 is seconds with precision to the thousandth place. 'Z' is the timezone for UTC, colloquially known as Zulu time.

If you take a look at this table in the Python 2.x docs, the %S argument can only handle the range [00, 61] inclusive with no decimal points. The 61 is to account for leap seconds. This is why your string formats don't match. You'll need to remove the three zeros following the decimal point from your string.