Search code examples
pythondatetimeepochstrptime

python convert datetime formatted string to seconds


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.


Solution

  • 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.