Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 652
static_rtti Avatar asked Nov 08 '09 20:11

static_rtti


People also ask

How do you convert a Date object to a datetime object in Python?

Convert Date to DateTime Using the datetime Combine Method in Python. In this method, we will first import the date and datetime from the datetime built-in object, then we will extract the current date and minimum time respectively. Both objects will be merged using Python datetime combine built-in method.

Which function converts a datetime object to a string?

strftime. Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.


2 Answers

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)) 
like image 100
Rod Hyde Avatar answered Oct 19 '22 05:10

Rod Hyde


Like this:

>>> structTime = time.localtime() >>> datetime.datetime(*structTime[:6]) datetime.datetime(2009, 11, 8, 20, 32, 35) 
like image 38
Nadia Alramli Avatar answered Oct 19 '22 05:10

Nadia Alramli