python输出时间分钟小时_Python:在两个日期时间之间打印所有小时来计算夏令时...

我想在给定的两个日期时间之间打印所有时间来计算夏令时.

这是我开始的:

from datetime import date, timedelta as td, datetime

d1 = datetime(2008, 8, 15, 1, 1, 0)

d2 = datetime(2008, 9, 15, 1, 12, 4)

while(d1

d1 = d1 + td(hours=1)

print d1

但是我如何为白天节省时间做些什么呢.如何跳跃或增加一小时的夏令时?

编辑:

根据以下建议,我编写了以下代码,它仍然打印了2016年的夏令时.

import pytz

from datetime import date, timedelta as td, datetime

eastern = pytz.timezone('US/Eastern')

d1 = eastern.localize(datetime(2016, 3, 11, 21, 0, 0))

d2 = eastern.localize(datetime(2016, 3, 12, 5, 0, 0))

d3 = eastern.localize(datetime(2016, 11, 4, 21, 0, 0))

d4 = eastern.localize(datetime(2016, 11, 5, 5, 0, 0))

while(d1

print d1

d1 = d1 + td(hours=1)

while(d3

print d3

d3 = d3 + td(hours=1)

输出:

2016-03-11 21:00:00-05:00

2016-03-11 22:00:00-05:00

2016-03-11 23:00:00-05:00

2016-03-12 00:00:00-05:00

2016-03-12 01:00:00-05:00

2016-03-12 02:00:00-05:00

2016-03-12 03:00:00-05:00

2016-03-12 04:00:00-05:00

2016-11-04 21:00:00-04:00

2016-11-04 22:00:00-04:00

2016-11-04 23:00:00-04:00

2016-11-05 00:00:00-04:00

2016-11-05 01:00:00-04:00

2016-11-05 02:00:00-04:00

2016-11-05 03:00:00-04:00

2016-11-05 04:00:00-04:00

编辑2:

期望的结果:

在三月小时跳过,凌晨两点它变成凌晨3点.

2016-03-11 23:00:00-05:00

2016-03-12 00:00:00-05:00

2016-03-12 01:00:00-05:00

2016-03-12 03:00:00-05:00

在11月,凌晨2点增加一小时,所以重复上午2点,它应该是:

2016-11-04 23:00:00-04:00

2016-11-05 00:00:00-04:00

2016-11-05 01:00:00-04:00

2016-11-05 02:00:00-04:00

2016-11-05 02:00:00-04:00

2016-11-05 03:00:00-04:00

最佳答案 根据pytz,当你想使用本地时间做datetime算术时,你需要使用normalize()方法来处理夏令时和其他时区转换因此你应该修改你的代码来包含这个

import pytz

from datetime import date, timedelta as td, datetime

eastern = pytz.timezone('US/Eastern')

d1 = eastern.localize(datetime(2016, 3, 11, 21, 0, 0))

d2 = eastern.localize(datetime(2016, 3, 12, 5, 0, 0))

d3 = eastern.localize(datetime(2016, 11, 4, 21, 0, 0))

d4 = eastern.localize(datetime(2016, 11, 5, 5, 0, 0))

while(d1

print d1

d1 = eastern.normalize(d1 + td(hours=1))

while(d3

print d3

d3 = eastern.normalize(d3 + td(hours=1))

检查pytz更多here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值