Created
July 6, 2012 02:21
-
-
Save mrluanma/3057655 to your computer and use it in GitHub Desktop.
Convert datetime to Unix timestamp.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def datetime2stamp(year, month, day, hour, minute, second): | |
timestamp = 0 | |
for y in range(year - 1, 1969, -1): | |
if is_leap_year(y): | |
day += 366 | |
else: | |
day += 365 | |
month_day = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] | |
day += month_day[month - 1] | |
if (is_leap_year(year) and month > 2): | |
day += 1 | |
day -= 1 # today is not over yet | |
timestamp += day * 86400 | |
timestamp += hour * 3600 | |
timestamp += minute * 60 | |
timestamp += second | |
return timestamp | |
def is_leap_year(year): | |
if year % 4 == 0: | |
if year % 100 == 0: | |
if year % 400 != 0: | |
return False | |
return True | |
return False |
@lxneng 对,的确可以,这个只是实现着玩,用来验证一个 C 实现的算法是否正确。需要注意的是 time.mktime 是 local time,如果要 GMT 的 unix timestamp 的话可以用 calendar.timegm。并且这里的 is_leap_year 和 calendar.isleap 是等价的。
恩, 呵呵
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这样不是可以么??