How do you convert a time.struct_time object into a datetime object?


Question

How do you convert a Python time.struct_time object into a datetime.datetime object?

I have a library that provides the first one and a second library that wants the second one.

1
271
6/3/2019 10:15:18 PM

Accepted Answer

Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.

from datetime import datetime
from time import mktime

dt = datetime.fromtimestamp(mktime(struct))
368
3/31/2019 11:49:35 PM

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon