如果内存中的每个整数都构造一个datetime对象,那么有比以下更好的方法。
atoi(datetime(year,month,day,hour,minute,second).stftime("%s"))
答案 0 :(得分:4)
您可以将time.mktime()
与datetime.timetuple()
一起使用:
dt = datetime.datetime(year, month, day, hour, minute, second)
unix_time = time.mktime(dt.timetuple())
或者,如果您不需要datetime
对象,则可以构建与time.struct_time
兼容的9元组,并将其直接传递给mktime()
:
time_tuple = (year, month, day, hour, minute, second, day_of_week, day_in_year, dst)
unix_time = time.mktime(time_tuple)
请注意time.mktime()
does not take into account day_of_week
and day_in_year
,因此请随意将它们设置为-1
。
您也可以将dst
设置为-1
,表示mktime
应自动确定DST是否生效。
使用Cython,您还可以构建struct tm
并将其直接传递给mktime(3)
:
from libc.time cimport tm, mktime
cdef tm time_tuple = {
'tm_sec': second,
'tm_min': minute,
'tm_hour': hour,
'tm_mday': day,
'tm_mon': month - 1,
'tm_year': year - 1900,
'tm_wday': day_of_week,
'tm_yday': day_in_year,
'tm_isdst': dst,
'tm_zone': NULL,
'tm_gmtoff': 0,
}
unix_time = mktime(&time_tuple)
这正是Python中的what happens behind the scenes when you call time.mktime()
。
同样,tm_wday
/ day_of_week
和tm_yday
/ day_in_year
会被忽略,dst
可能会-1
。