views:

1563

answers:

2

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

+8  A: 

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)
Nadia Alramli
Don't forget to #import time, datetime
jhwist
@jhwist - some things people can be trusted to figure it out on their own :)
orip
I like this one. It's concise.
twneale
+15  A: 

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 time import mktime
from datetime import datetime

dt = datetime.fromtimestamp(mktime(struct))
Rod Hyde
+1, I like this more than my solution :)
Nadia Alramli
@Nadia - thanks :)
Rod Hyde
thanx it solves my problem tooooo....
Dhaval dave