Python3 格式化时间

qbit 经常用到当前时间和相对时间,用来统计程序执行的效率,简单记一下,便于 copy。

模块

相对时间

>>> import time

# 相对时间
>>> startTime = time.time()
>>> '%.2fs' % (time.time() - startTime)    
'24.51s'

# 本地时间
>>> time.localtime()
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=24, 
                    tm_hour=19, tm_min=40, tm_sec=49, 
                    tm_wday=0, tm_yday=55, tm_isdst=0)

# UTC 时间
>>> time.gmtime()
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=24, 
                    tm_hour=11, tm_min=40, tm_sec=51, 
                    tm_wday=0, tm_yday=55, tm_isdst=0)

格式化当前时间

# 格式化当前时间
>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2020-02-24 19:44:16'
# 格式化本地时间
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
Out[70]: '2020-02-24 19:44:18'
# 格式化 UTC 时间
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
'2020-02-24 11:44:19'

时间戳与时间的转换

# 将时间戳转化为时间
>>> time.localtime(1521793044.7850916)
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=23, tm_hour=16, 
  tm_min=17, tm_sec=24, tm_wday=4, tm_yday=82, tm_isdst=0)
  
# 将时间戳转化为可读字符串
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1521793044.7850916))
'2018-03-23 16:17:24'
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
'2018-03-23 16:17:29'

# 将时间转化为时间戳
>>> time.strptime('2016-05-05 20:28:54', '%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=5, tm_hour=20, tm_min=28, 
tm_sec=54, tm_wday=3, tm_yday=126, tm_isdst=-1)
>>> time.mktime(time.strptime('2016-05-05 20:28:54', '%Y-%m-%d %H:%M:%S'))
1462451334.0

# 可读字符串 -> 时间戳 -> 可读字符串
>>> time.strftime('%Y-%m-%d %H:%M:%S', 
  time.strptime('2018-03-23 16:17:24', '%Y-%m-%d %H:%M:%S'))
'2018-03-23 16:17:24'

时区

from datetime import datetime, timedelta, timezone

# 0 区
dt0 = datetime.utcnow().replace(tzinfo=timezone.utc)
print(dt0.strftime('%Y-%m-%d %H:%M:%S'))    # 2020-02-24 12:37:08

# 东八区
dt8 = dt0.astimezone(timezone(timedelta(hours=8)))
print(dt8.strftime('%Y-%m-%d %H:%M:%S'))    # 2020-02-24 20:37:08

# 时间转时间戳
timestamp0 = datetime.timestamp(dt0)
print(timestamp0)   # 1582547828.433725(时间戳不变)

timestamp8 = datetime.timestamp(dt8)
print(timestamp8)   # 1582547828.433725(时间戳不变)

# 将时间戳按东八区时间打印(2020-02-24 20:37:08)
print(
        datetime.fromtimestamp(1582547828.433725)
                .astimezone(timezone(timedelta(hours=8)))
                .strftime('%Y-%m-%d %H:%M:%S')
    )
本文出自 qbit snap

你可能感兴趣的:(时间戳,time,时间,datetime,python)