python - 带时区的日期时间到纪元 [英] python - datetime with timezone to epoch

查看:28
本文介绍了python - 带时区的日期时间到纪元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在计算现在时代和当前时代时代的开始.

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 - 带时区的日期时间到纪元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆