在时区之间切换 [英] Change between timezones

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

问题描述

当我尝试使用 datetime 模块

In [31]: datetime.now()
Out[31]: datetime.datetime(2018, 6, 6, 8, 59, 35, 49991)
In [32]: str(datetime.now())
Out[32]: '2018-06-06 08:59:45.633486'

我打算更改为本地时间,但在数十个时区模块和第三方程序包中迷失了pytz。

I intend to change to my local time but were lost in dozens of timezone modules and third-party package as pytz.

如何直接在两个时区之间进行更改

How could I change betweens timezones in a straight forward way?

推荐答案

内置的 datetime 模块为您提供了基本的方法类和数据结构来处理时区,但它不包含实际的时区数据。这是因为偶尔会更新和修订此类数据,并且您不希望将其硬编码到Python发行版中。这就是 pytz 模块出现的地方,可以单独安装并保持最新。

The built-in datetime module gives you the basic classes and data structures to deal with timezones, but it does not contain actual timezone data. That is because such data is occasionally updated and revised, and you wouldn't want that hardcoded into the Python distribution. That's where the pytz module comes in, which can be installed and kept up-to-date separately.

在实践中,您通常处理 datetime.datetime pytz.timezone

In practice you mostly deal with datetime.datetime and pytz.timezone:

from datetime import datetime
import pytz

datetime.now(pytz.timezone('Asia/Tokyo'))

如果您只在UTC工作,那是Python内置的唯一时区:

If you're only working in UTC, that's the only timezone Python has built-in:

from datetime import datetime, timezone

datetime.now(timezone.utc)

使用 datetime.astimezone ,<$ c时,应仔细阅读pytz使用说明。 $ c>本地化以及何时将时区作为参数传递给 datetime 函数: http://pytz.sourceforge.net/#example-usage

You should carefully read the pytz usage notes when to use datetime.astimezone, localize and when to pass the timezone as argument to a datetime function: http://pytz.sourceforge.net/#example-usage.

这篇关于在时区之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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