Convert time.structure_time object to datetime object

Asked 1 years ago, Updated 1 years ago, 87 views

In the code I write, the first library receives time.structure_time and the second library receives datetime as a factor. How do I replace the time.structure_time object with the datetime object?

python datetime convert

2022-09-22 10:59

1 Answers

from time import mktime, gmtime
from datetime import datetime

rightnow = gmtime()
print("gmtime:\t\t\t\t\t\t\t\t\t", rightnow)
print("mktime(mytime):\t\t\t\t\t\t\t", mktime(rightnow))
print("type(mktime(rightnow)):\t\t\t\t\t", type(mktime(rightnow)))
print("datetime.fromtimestamp(mktime(rightnow)):", datetime.fromtimestamp(mktime(rightnow)))

Output:

gmtime:                                  time.struct_time(tm_year=2016, tm_mon=1, tm_mday=27, tm_hour=2, tm_min=56, tm_sec=4, tm_wday=2, tm_yday=27, tm_isdst=0)
mktime(mytime):                          1453830964.0
type(mktime(rightnow)):                  <class 'float'>
datetime.fromtimestamp(mktime(rightnow)): 2016-01-27 02:56:04

Alternatively, you can simply slice structure_time to index 6 and then convert it right away.

from time import localtime
from datetime import datetime

structTime = localtime()
print("localtime()\t\t\t\t\t:", structTime)
print("localtime()[:6]\t\t\t\t:", structTime[:6])
print("datetime(*structTime[:6])\t:", datetime(*structTime[:6]))

Output:

localtime()                 : time.struct_time(tm_year=2016, tm_mon=1, tm_mday=27, tm_hour=12, tm_min=5, tm_sec=4, tm_wday=2, tm_yday=27, tm_isdst=0)
localtime()[:6]             : (2016, 1, 27, 12, 5, 4)
datetime(*structTime[:6])   : 2016-01-27 12:05:04


2022-09-22 10:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.