28

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anthony
  • 12,407
  • 12
  • 64
  • 88

2 Answers2

52

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • It should be noted that this assumes that `timetup` refers to UTC ('Z'). – FObersteiner Jul 22 '20 at 09:04
  • @MrFuppes only because I used `time.gmtime()` to create it; the OP didn’t show how they had created theirs. You can also use `time.localtime()`, but given that the expected output included a `Z` (UTC timezone) marker and the formatted time matched their `timeup` value, it was a reasonable assumption that they had used `time.gmtime()` to create it. – Martijn Pieters Jul 22 '20 at 10:00
0
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'

xuehui
  • 825
  • 1
  • 8
  • 17