简体   繁体   中英

how to convert unix timestamp with z to date time in python

how would i convert this timestamp '20141031131429Z' to 31 october 2014 in python

>>>datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%S%Z" )

the above code gives me an error shown below:

ValueError: time data '20141031131429Z' does not match format '%Y%m%d%H%M%S%Z'

Remove the % in front of the Z :

d = datetime.datetime.strptime("20141031131429Z", "%Y%m%d%H%M%SZ" )
print(d.strftime("%d %B %Y"))

Output:

31 October 2014

Set the documentation for the strftime() and strptime() behavior .

That's not a unix timestamp (which are parsed with %s in strftime/strptime) - it looks like iCalendar form #2 (RFC 2445). A module like iCalendar might help you parse that without having to hardcode which form is used.

Once you have a datetime object, it can be used to retrieve any other format:

>>> dt=datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%SZ" )
>>> dt.strftime('%d %B %Y')
'31 October 2014'
>>> dt.strftime('%x')
'10/31/14'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM