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.
To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.
Example: Use timestamp() method timestamp() method to easily convert the datetime object to seconds. This method will only be useful if you need the number of seconds from 1970-01-01 UTC. It returns a float value representing even fractions of a second.
Multiply the hours by 60 to convert it to minutes, i.e., 1 hr × 60 = 60 minutes . Multiply the minutes by 60 to obtain the number of seconds, i.e., 60 minutes × 60 = 3600 seconds .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With