如何获得一天的第一个日期时间? [英] How to get the first datetime of a day?

查看:114
本文介绍了如何获得一天的第一个日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用pytz和Python 3.4,如何获得给定时区的第一个 datetime (让我们说,2014-10-19) 'America / Sao_Paulo')?

Using pytz and Python 3.4, how to get the first datetime of a given day (lets say, 2014-10-19), in a given timezone (lets say 'America/Sao_Paulo')?

推荐答案

使用 localize()方法附加时区:

from datetime import datetime
import pytz # $ pip install pytz

tz = pytz.timezone('America/Sao_Paulo')    
naive = datetime(2014, 10, 19)
aware = tz.localize(naive, is_dst=None)

如果运行代码;它生成 NonExistentTimeError 。如何处理此错误取决于应用程序,例如,在午夜附近获得一些有效的本地时间:

If you run the code; it generates NonExistentTimeError. How to deal with this error depends on the application e.g., to get some valid local time near the midnight:

aware = tz.normalize(tz.localize(naive, is_dst=False))

或者你可以增加时间分钟分钟,直到您得到一个有效的本地(圣保罗)时间:

Or you could increment the time minute by minute until you'll get a valid local (Sao Paulo) time:

from datetime import datetime, timedelta
import pytz # $ pip install pytz

tz = pytz.timezone('America/Sao_Paulo')
d = naive = datetime(2014, 10, 19)
while True:
    try:
        aware = tz.localize(d, is_dst=None)
    except pytz.AmbiguousTimeError:
        aware = tz.localize(d, is_dst=False)
        assert tz.localize(d, is_dst=False) > tz.localize(d, is_dst=True)
        break
    except pytz.NonExistentTimeError:
        d += timedelta(minutes=1) # try future time
        continue
    else:
        break

结果:

>>> aware
datetime.datetime(2014, 10, 19, 1, 0, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRST-1 day, 22:00:00 DST>
>>> aware.strftime('%Y-%m-%d %H:%M:%S %Z%z')
'2014-10-19 01:00:00 BRST-0200'

注意:第一个有效时间是 01:00 on那天,时区是UTC后两个小时(local = utc - 2)。

Note: the first valid time is 01:00 on that day. And the timezone is two hours behind UTC (local = utc - 2).

这篇关于如何获得一天的第一个日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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