Python 中获得今天的 Unix Timestamp

2011-03-07 23:53:24 +08:00
 Livid
>>> import datetime
>>> import time
>>> int(time.mktime(datetime.date.today().timetuple()))
1299427200

还有更简单的办法么?
7769 次点击
所在节点    Python
6 条回复
GordianZ
2011-03-08 00:22:22 +08:00
import time
print int(time.time())
GordianZ
2011-03-08 00:22:57 +08:00
@Livid oh, sry, didn't notice you need time for the day...
Then probably yours is the easiest way already :(
Livid
2011-03-08 00:23:21 +08:00
抱歉我没有表述清楚。

是希望获得今天 0 点时候的 timestamp。
keakon
2011-03-08 00:40:26 +08:00
貌似用calendar.timegm更好,mktime会返回浮点数,而且时区可能有问题。不过也没什么能简化的。
diamondtin
2011-03-08 17:39:55 +08:00
def mid_night_timestamp():
timestamp = int(time.time())
if timestamp % 86400 == 57600: //57600 = 86400 + (60 * 60 * -8)
return timestamp
else:
return timestamp / 86400 * 86400 + (60 * 60 * -8)

This is faster :D
不过仅在时区固定的时候有效,替换一下时区offset就可以了。如果在TimeZone aware的环境,需要用tzinfo的offset修改一下。
Livid
2011-03-08 18:14:50 +08:00
@keakon 嗯,确实应该在服务器端保存 UTC 时间。

感谢!!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/9444

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX