utcoffset() 函數用於返回一個 timedelta 對象,該對象表示本地時間和 UTC 時間之間的差異。
- 該函數用於在 datetime 模塊的 datetime 類中使用。
- 這裏 utcoffset 的範圍是“timedelta(hours=24) <= offset <= timedelta(hours=24)”。
- 如果偏移量在 UTC 以東,那麽它被認為是正數,如果偏移量在 UTC 以西,那麽它被認為是負數。由於一天有 24 小時,因此 -timedelta(24) 和 timedelta(24) 是可能的最大值。
用法:utcoffset()
參數:此函數不接受任何參數。
Return values:此函數返回一個 timedelta 對象,表示本地時間和 UTC 時間之間的差異。
範例1:這裏的輸出是 None,因為 now() 函數以 UTC 格式返回日期和時間,因此本地時間即 now() 函數返回的本地時間與 UTC 時間之間的差異是 none。
Python3
# Python3 code for getting
# the difference between the
# local time and UTC time
# Importing datetime and pytz module
from datetime import datetime
import pytz
# Calling the now() function to get
# current date and time
date_time = datetime.now()
# Calling the utcoffset() function
# over the above intitialized datetime
print(date_time.utcoffset())
輸出:
None
範例2:尋找時間的偏移
Python3
# Python3 code for getting
# the difference between the
# local time and UTC time
# Importing datetime and pytz module
from datetime import datetime
import pytz
# Calling the now() function to
# get current date and time
naive = datetime.now()
# adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = timezone.localize(naive)
# Calling the utcoffset() function
# over the above localized time
print("Time ahead of UTC by:", aware1.utcoffset())
輸出:
Time ahead of UTC by:5:30:00
範例3:查找時間偏移
Python3
# Python3 code for getting
# the difference between the
# local time and UTC time
# Importing datetime and pytz module
from datetime import datetime
import pytz
# Calling the now() function to
# get current date and time
naive = datetime.now()
# adding a timezone
timezone = pytz.timezone("Asia/Tokyo")
aware1 = timezone.localize(naive)
# Calling the utcoffset() function
# over the above localized time
print("Time ahead of UTC by:", aware1.utcoffset())
輸出:
Time ahead of UTC by:9:00:00
相關用法
- Python datetime.timetz()用法及代碼示例
- Python DateTime weekday()用法及代碼示例
- Python datetime.tzname()用法及代碼示例
- Python timedelta total_seconds()用法及代碼示例
- Java Vector removeElement()用法及代碼示例
- Java Vector removeRange()用法及代碼示例
- Java Vector setSize()用法及代碼示例
- Java Vector trimToSize()用法及代碼示例
- Java ConcurrentLinkedDeque peek()用法及代碼示例
- Java ConcurrentLinkedDeque poll()用法及代碼示例
- Java Vector setElementAt()用法及代碼示例
- Java Vector removeAllElements()用法及代碼示例
- Java CopyOnWriteArraySet toArray()用法及代碼示例
- Java TreeSet pollLast()用法及代碼示例
- Java Vector ensureCapacity()用法及代碼示例
- Java ConcurrentLinkedDeque iterator()用法及代碼示例
- Java LinkedBlockingDeque drainTo()用法及代碼示例
- Java LinkedList toArray()用法及代碼示例
- Java ConcurrentLinkedDeque descendingIterator()用法及代碼示例
- Java CopyOnWriteArraySet containsAll()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Python datetime.utcoffset() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。