Python datetime.utcoffset() 方法和示例
utcoffset()函数用于返回一个 timedelta 对象,该对象表示本地时间和 UTC 时间之间的差异。
- 该函数用于在 datetime 模块的 datetime 类中使用。
- 这里 utcoffset 的范围是“timedelta(hours=24) <= offset <= timedelta(hours=24)”。
- 如果偏移量在 UTC 以东,那么它被认为是正数,如果偏移量在 UTC 以西,那么它被认为是负数。由于一天有 24 小时,因此 -timedelta(24) 和 timedelta(24) 是可能的最大值。
Syntax: utcoffset()
Parameters: This function does not accept any parameter.
Return values: This function returns a timedelta object representing the difference between the local time and UTC time.
实施例1:在此输出是无因为现在()函数返回的日期和时间UTC格式,因此本地时间,即之间的差,现在返回()函数和UTC时间是没有的。
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())
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())
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())
输出:
None
示例 2:查找时间偏移量
蟒蛇3
# 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:查找时间偏移
蟒蛇3
# 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