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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。