使用 cython 生成 unix 时间戳

using cython to generate a unix timestamp

如果你有内存中的每个整数来构造一个日期时间对象,是否有比以下更好的方法。

atoi(datetime(year,month,day,hour,minute,second).stftime("%s"))

您可以使用 time.mktime() together with datetime.timetuple():

dt = datetime.datetime(year, month, day, hour, minute, second)
unix_time = time.mktime(dt.timetuple())

或者,如果不需要datetime对象,可以构造一个兼容time.struct_time的九元组,直接传给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应该自动判断夏令时是否生效


使用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_weektm_yday/day_in_year被忽略,dst可能是-1