Python datetime.utcoffset() 方法
datetime.utcoffset() 方法用于 datetime 模块的 datetime 类。
它使用该类的一个实例并返回一个 timedelta 实例,该实例对应于给定实例中指定的 tzinfo 的 UTC 偏移量。
模块:
import datetime
类:
from datetime import datetime
用法:
utcoffset()
参数:
- None
返回值:
返回类型是一个 timedelta 对象,表示本地时间和 UTC 时间之间的差异。
utcoffset 的范围:-timedelta(hours=24) <= offset <= timedelta(hours=24)
如果偏移量在 UTC 以东,那么它被认为是正的,如果它在 UTC 以西,那么它就是负的。由于一天有 24 小时,因此 -timedelta(24) 和 timedelta(24) 是可能的最大值。
例:
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())
输出
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
相关用法
- Python datetime astimezone()用法及代码示例
- Python datetime timetuple()用法及代码示例
- Python datetime timetz()用法及代码示例
- Python datetime isocalendar()用法及代码示例
- Python datetime date()用法及代码示例
- Python datetime isoformat()用法及代码示例
- Python datetime __str__()用法及代码示例
- Python datetime time()用法及代码示例
- Python datetime weekday()用法及代码示例
- Python datetime tzname()用法及代码示例
- Python datetime replace()用法及代码示例
- Python datetime strftime()用法及代码示例
- Python datetime toordinal()用法及代码示例
- Python datetime isoweekday()用法及代码示例
- Python datetime.timedelta()用法及代码示例
- Python datetime.tzinfo()用法及代码示例
- Python date toordinal()用法及代码示例
- Python date replace()用法及代码示例
- Python date strftime()用法及代码示例
- Python date weekday()用法及代码示例
注:本文由纯净天空筛选整理自 Python datetime utcoffset() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。