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?

2 Answers 2

53

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It should be noted that this assumes that timetup refers to UTC ('Z').
@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.
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.