Python datetime.astimezone()方法 (Python datetime.astimezone() Method)
datetime.astimezone() method is used to manipulate objects of datetime class of module datetime.
datetime.astimezone()方法用于操作模块datetime的datetime类的对象。
It uses an instance of the class and returns a datetime object with new tzinfo attribute tz. It works on a datetime class instance.
它使用该类的实例,并返回具有新tzinfo属性tz的datetime对象。 它适用于datetime类实例。
Module:
模块:
import datetime
Class:
类:
from datetime import datetime
Syntax:
句法:
astimezone(tz)
Parameter(s):
参数:
tz - timezone information which should be changed.
tz-应更改的时区信息。
Return value:
返回值:
Returns a datetime object with new tzinfo attribute tz.
返回具有新的tzinfo属性tz的日期时间对象。
Example:
例:
from datetime import datetime
import pytz
naive= datetime.now()
## Tzinfo is missing from the time object
## which is naive
print("Tzinfo:",naive.tzinfo)
print()
## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = naive.astimezone(timezone)
print("Tzinfo:",aware1.tzinfo)
print()
## After adding the timezone info,
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = aware1.astimezone(timezone)
print("Initial tzinfo:",aware1.tzinfo)
print("Final tzinfo:",aware2.tzinfo)
print()
## No timezone was defined for naive
print(naive)
## Timezone changed from None to Asia/Kolkata
## for aware1 object
print(aware1)
## Timezone changed from Asia/Kolkata to
## Asia/Tokyo for aware2 object
print(aware2)
Output
输出量
Tzinfo: None
Tzinfo: Asia/Kolkata
Initial tzinfo: Asia/Kolkata
Final tzinfo: Asia/Tokyo
2020-04-30 18:44:12.784666
2020-05-01 00:14:12.784666+05:30
2020-05-01 03:44:12.784666+09:00
翻译自: https://www.includehelp.com/python/datetime-astimezone-method-with-example.aspx