首页 > 解决方案 > python datetime function for different type of timezone

问题描述

I would like to write a function different type of time zone. In this example I am in Ontario and want to winnipeg time.

def winnipeg_time():

x = datetime.datetime.now('America/Winnipeg')
print ('x')

Error I get : tzinfo argument must be None or of a tzinfo subclass, not type 'str

标签: pythondatetime

解决方案


您可以使用 指定tzinfo子类gettz()。要考虑的另一个选项是用于astimezone()指定时区。

以下是这两个选项的示例:

from datetime import datetime
import pytz
from dateutil.tz import tz

aw = pytz.timezone('America/Winnipeg')
x = datetime.now().astimezone(aw)
print(f'The pytz datetime in Winnipeg tz is {x}')

x2 = datetime.now(tz.gettz('America/Winnipeg'))
print(f'The gettz datetime in Winnipeg tz is {x2}')

结果:

The pytz datetime in Winnipeg tz is 2020-04-20 13:54:27.600227-05:00
The gettz datetime in Winnipeg tz is 2020-04-20 13:54:27.600544-05:00

推荐阅读