Python datetime.utcoffset()方法 (Python datetime.utcoffset() Method)
datetime.utcoffset() method is used in the datetime class of module datetime.
datetime.utcoffset()方法在模块datetime的datetime类中使用。
It uses an instance of the class and returns a timedelta instance corresponding to UTC offset of the tzinfo specified in the instance given.
它使用该类的实例,并返回与给定实例中指定的tzinfo的 UTC偏移量对应的timedelta实例。
Module:
模块:
import datetime
Class:
类:
from datetime import datetime
Syntax:
句法:
utcoffset()
Parameter(s):
参数:
None
没有
Return value:
返回值:
The return type is a timedelta object representing the difference between the local time and UTC time.
返回类型是一个timedelta对象,表示本地时间和UTC时间之间的时差。
Range of the utcoffset: -timedelta(hours=24) <= offset <= timedelta(hours=24)
utcoffset的范围: -timedelta(hours = 24)<=偏移量<= timedelta(hours = 24)
If the offset is east of UTC, then it is considered positive and if it is west of UTC, it is negative. Since there are 24 hours in a day, -timedelta(24) and timedelta(24) are the largest values possible.
如果偏移量在UTC以东,则视为正值;如果偏移量在UTC以西,则为负值。 由于一天中有24小时,因此-timedelta(24)和timedelta(24)是可能的最大值。
Example:
例:
from datetime import datetime
import pytz
naive= datetime.now()
## Tzinfo is missing from the time object
## which is naive
print(naive)
print(naive.tzinfo)
print(naive.utcoffset())
print()
## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = timezone.localize(naive)
print(aware1)
print(aware1.tzinfo)
print("Time ahead of UTC by:", aware1.utcoffset())
print()
## After adding the timezone info,
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = timezone.localize(naive)
print(aware2)
print(aware2.tzinfo)
print("Time ahead of UTC by:", aware2.utcoffset())
print()
timezone = pytz.timezone("America/New_York")
aware3 = timezone.localize(naive)
print(aware3)
print(aware3.tzinfo)
## timedelta comes as -1 day 20 hrs
## which is equal to -4 hrs
print("Time behind to UTC by:", aware3.utcoffset())
print()
## You can also use the astimezone
## function of datetime to
timezone = pytz.timezone("Europe/Berlin")
aware4 = naive.astimezone(timezone)
print(aware4)
print(aware4.tzinfo)
print("Time ahead of UTC by:", aware4.utcoffset())
Output
输出量
2020-04-30 20:35:51.516509
None
None
2020-04-30 20:35:51.516509+05:30
Asia/Kolkata
Time ahead of UTC by: 5:30:00
2020-04-30 20:35:51.516509+09:00
Asia/Tokyo
Time ahead of UTC by: 9:00:00
2020-04-30 20:35:51.516509-04:00
America/New_York
Time behind to UTC by: -1 day, 20:00:00
2020-04-30 22:35:51.516509+02:00
Europe/Berlin
Time ahead of UTC by: 2:00:00
翻译自: https://www.includehelp.com/python/datetime-utcoffset-method-with-example.aspx