Skip to content

Instantly share code, notes, and snippets.

@mrluanma
Created July 6, 2012 02:21
Show Gist options
  • Save mrluanma/3057655 to your computer and use it in GitHub Desktop.
Save mrluanma/3057655 to your computer and use it in GitHub Desktop.
Convert datetime to Unix timestamp.
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
Copy link

lxneng commented Jul 6, 2012

>>> import time
>>> from datetime import datetime
>>> time.mktime(datetime.now().timetuple())
1341544940.0

这样不是可以么??

@mrluanma
Copy link
Author

mrluanma commented Jul 6, 2012

@lxneng 对,的确可以,这个只是实现着玩,用来验证一个 C 实现的算法是否正确。需要注意的是 time.mktime 是 local time,如果要 GMT 的 unix timestamp 的话可以用 calendar.timegm。并且这里的 is_leap_year 和 calendar.isleap 是等价的。

@lxneng
Copy link

lxneng commented Jul 6, 2012

恩, 呵呵

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment