from datetime import datetime time_str = "2016-09-10 4:23:21" time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')# 根据字符串本身的格式进行转换 time.strftime('%Y-%m-%d-%H-%M') Out>>'2016-09-10-04-23'
python 将带有TZ的UTC时间字符串,转换成本地时间
整个地球分为二十四时区,每个时区都有自己的本地时间。在国际无线电通信中,为统一而普遍使用一个标准时间,称为通用协调时(UTC, Universal Time Coordinated)。UTC与格林尼治平均时(GMT, Greenwich Mean Time)一样,都与英国伦敦的本地时相同。UTC与GMT含义完全相同。北京时区是东八区,领先UTC 8个小时。所以将UTC装换成北京时间时,需要加上8小时。
Copy import datetime
origin_date_str = "2019-07-26T08:20:54Z"
utc_date = datetime . datetime . strptime (origin_date_str, "%Y-%m- %d T%H:%M:%SZ" )
local_date = utc_date + datetime . timedelta (hours = 8 )
local_date_str = datetime . datetime . strftime (local_date , '%Y-%m- %d %H:%M:%S' )
print (local_date_str ) # 2019-07-26 16:20:54
import datetime
utc = "2017-07-28T08:28:47.776Z"
UTC_FORMAT = "%Y-%m- %d T%H:%M:%S. %f Z"
utc_time = datetime . datetime . strptime (utc, UTC_FORMAT)
local_time = utc_time + datetime . timedelta (hours = 8 )
print (local_time) # 2017-07-28 16:28:47.776000
使用Python标准库获取当前北京时间 (无需pytz)
Copy from datetime import datetime
from datetime import timedelta
from datetime import timezone
SHA_TZ = timezone (
timedelta (hours = 8 ),
name = 'Asia/Shanghai' ,
)
# 协调世界时
utc_now = datetime . utcnow (). replace (tzinfo = timezone.utc)
print (utc_now, utc_now. tzname ())
print (utc_now. date (), utc_now. tzname ())
# 北京时间
beijing_now = utc_now . astimezone (SHA_TZ)
print (beijing_now, beijing_now. tzname ())
print (beijing_now. date (), beijing_now. tzname ())
# 系统默认时区
local_now = utc_now . astimezone ()
print (local_now, local_now. tzname ())
print (local_now. date (), local_now. tzname ())
计算结果
2020 - 05 - 01 11 : 31 : 20.692283 + 00 : 00 UTC
2020 - 05 - 01 UTC
2020 - 05 - 01 19 : 31 : 20.692283 + 08 : 00 Asia / Shanghai
2020 - 05 - 01 Asia / Shanghai
2020 - 05 - 01 21 : 31 : 20.692283 + 10 : 00 AEST
2020 - 05 - 01 AEST