python - 具有时区的datetime [英] python - datetime with timezone to epoch

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

问题描述

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

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.)

请参阅 JFSebastian的答案

这里是一个代码,演示了一个值 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 - 具有时区的datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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