使用 cython 生成 unix 时间戳

Mic*_* WS 2 python cython unix-timestamp python-datetime

如果您在内存中拥有每个整数来构造 datetime 对象,是否有比以下更好的方法。

atoi(datetime(year,month,day,hour,minute,second).stftime("%s"))
Run Code Online (Sandbox Code Playgroud)

And*_*ini 5

您可以time.mktime()datetime.timetuple()以下一起使用:

dt = datetime.datetime(year, month, day, hour, minute, second)
unix_time = time.mktime(dt.timetuple())
Run Code Online (Sandbox Code Playgroud)

或者,如果您不需要该datetime对象,您可以构造一个兼容的 9 元组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)
Run Code Online (Sandbox Code Playgroud)

注意time.mktime()没有考虑day_of_weekday_in_year,所以随意设置它们-1

你也可以设置dst-1,表示mktime应该自动判断夏令时是否生效。


使用 Cython,您还可以构造 astruct 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)
Run Code Online (Sandbox Code Playgroud)

这正是time.mktime()在 Python 中调用时幕后发生的事情

同样,tm_wday/day_of_weektm_yday/day_in_year被忽略,dst可能是-1.