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?
To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'.
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
Python time strptime() Method Python time method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With