Python3 - 时间戳、时区和日期转换傻傻分不清楚

Python3 - 时间戳、时区和日期转换傻傻分不清楚

接触过很多程序老手,遇到时间戳、时区问题总是搞不清楚。今天主要分享下,如何正确的理解和使用时间戳、时区和日期。简单起见,我们只讨论两个库。

  • import pytz
  • from datetime import datetime

pytz 是一个老牌的时区数据库(Olson timezones database)。

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).

Almost all of the Olson timezones are supported.

1
pip3 install pytz

datetime 是 python 官方的标准库。本文的思路是借助这两个库,实现时间戳到日期字符串之间的转换。总体上,我们可以这样理解:

1
时间戳 = F(时区, 日期)

也就是说,日期只有配合上时区,才能得到正确的时间戳。反之亦然。

时间戳 转 日期字符串

我们看下三个时区(UTC,Asia/Shanghai,US/Eastern) ,在同一个时间戳下对应的日期。

1
2
3
4
5
6
7
8
9
10
11
ts = 1585670057
print (ts)
tz  = pytz.timezone('UTC')
tz1  = pytz.timezone('Asia/Shanghai')
tz2 = pytz.timezone('US/Eastern')
dtt = datetime.fromtimestamp(ts, tz)
dtt1 = datetime.fromtimestamp(ts, tz1)
dtt2 = datetime.fromtimestamp(ts, tz2)
print( dtt, tz)
print( dtt1, tz1)
print( dtt2, tz2)

输出

1
2
3
4
1585670057
2020-03-31 15:54:17+00:00 UTC
2020-03-31 23:54:17+08:00 Asia/Shanghai
2020-03-31 11:54:17-04:00 US/Eastern

可以看出,即使是同一个时间戳,在不同时区显示的日期是不一致的。

日期字符串 转 时间戳

1
2
3
4
5
6
7
8
9
new_dtt = datetime.strptime('2020-03-31 15:54:17', '%Y-%m-%d %H:%M:%S')
new_dtt1 = datetime.strptime('2020-03-31 23:54:17', '%Y-%m-%d %H:%M:%S')
new_dtt2 = datetime.strptime('2020-03-31 11:54:17', '%Y-%m-%d %H:%M:%S')
ts = tz.localize(new_dtt).timestamp()
ts1 = tz1.localize(new_dtt1).timestamp()
ts2 = tz2.localize(new_dtt2).timestamp()
print(ts, tz)
print(ts1, tz1)
print(ts2, tz2)

输出

1
2
3
1585670057.0 UTC
1585670057.0 Asia/Shanghai
1585670057.0 US/Eastern

可以看出,虽然日期不同,但时间戳是一致的。

以上代码完美实现了数字时间戳和日期字符串之间的完美转换,在 python3.7.6 测试通过。

Rating: