问题描述
在下面的代码中,我正在计算现在纪元和当前纪元的开始.
In the code below, I am calculating now epoch and beginning of current day epoch.
import time
import pytz
from datetime import datetime
tz1 = pytz.timezone('CST6CDT')
utc = pytz.timezone('UTC')
now = pytz.UTC.localize(datetime.utcnow())
now_tz = now.astimezone(tz1)
print now_tz
print now_tz.strftime('%s')
begin_day = now_tz.replace(hour=0, minute=0, second=0)
print begin_day
print begin_day.strftime('%s')
打印语句:
2012-08-28 13:52:21.595718-05:00
1346187141
2012-08-28 00:00:00.595718-05:00
1346137200
使用 CDT 时区将纪元转换为时间戳:1346187141 - 2012 年 8 月 28 日 15:52:21,1346137200 - 2012年8月28日02:00:00
Converting epochs to timestamp with CDT timezone: 1346187141 - Aug 28 2012 15:52:21, 1346137200 - Aug 28 2012 02:00:00
我希望第二个纪元是一天的开始,但现在是凌晨 2 点.转换为纪元时,它看起来仍在使用本地时区 PST.
I'd like the second epoch to be beginning of the day but it's 2 am. It looks like it is still using local timezone PST when converting to epoch.
我做错了什么?或者这可以用不同的方式完成吗?
What am I doing wrong ? or can this be done a different way?
谢谢!
推荐答案
注意:我的回答完全错误.(我想删除它,但直到接受标志被移除.)
NOTE: My answer is flat-out wrong. (I'd like to delete it, but am unable to do so until the accept flag is removed.)
请参阅 J.F.Sebastian 的回答.
这是演示 now_tz
值的代码,我们的两种方法会产生不同的结果.
Here is code demonstrating a value of now_tz
for which our two methods produce different results.
import calendar
import pytz
import datetime as dt
tz1 = pytz.timezone('US/Eastern')
utc = pytz.timezone('UTC')
now = utc.localize(dt.datetime(2002, 10, 28), is_dst=None)
now_tz = now.astimezone(tz1)
now_epoch = calendar.timegm(now_tz.utctimetuple())
begin_day = tz1.normalize(now_tz.replace(hour=0, minute=0, second=0))
midnight = tz1.localize(dt.datetime.combine(now_tz, dt.time(0, 0)), is_dst=None)
if begin_day != midnight:
print(begin_day)
# 2002-10-27 01:00:00-04:00 # my result -- is not midnight
print(midnight)
# 2002-10-27 00:00:00-04:00 # J.F.Sebastian's result is correct
<小时>
(原始答案已编辑)
(Original answer redacted)
这篇关于python - 带有时区的日期时间到纪元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!