Anthony
Anthony

Reputation: 12736

How do you convert a python time.struct_time object into a ISO string?

I have a Python object:

time.struct_time(tm_year=2013, tm_mon=10, tm_mday=11, tm_hour=11, tm_min=57, tm_sec=12, tm_wday=4, tm_yday=284, tm_isdst=0)

And I need to get an ISO string:

'2013-10-11T11:57:12Z'

How can I do that?

Upvotes: 28

Views: 41285

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

Using time.strftime() is perhaps easiest:

iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)

Demo:

>>> import time
>>> timetup = time.gmtime()
>>> time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
'2013-10-11T13:31:03Z'

You can also use a datetime.datetime() object, which has a datetime.isoformat() method:

>>> from datetime import datetime
>>> datetime(*timetup[:6]).isoformat()
'2013-10-11T13:31:03'

This misses the timezone Z marker; you could just add that.

Upvotes: 53

xuehui
xuehui

Reputation: 925

iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)

The last format charater ‘Z’ is not necessary, such as

iso = time.strftime('%Y-%m-%dT%H:%M:%S', timetup)

You will get time string like '2015-11-05 02:09:57'

Upvotes: 0

Related Questions