Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 941
Antonio Avatar asked Oct 11 '13 13:10

Antonio


People also ask

How do I convert ISO to datetime in Python?

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'.

How do you change time format in Python?

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.

How do you parse a string time in python?

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().

How do you convert time to seconds in Python?

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.


1 Answers

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.

like image 94
Martijn Pieters Avatar answered Oct 12 '22 08:10

Martijn Pieters