python时区

一点关于python里面时区的知识

时区

GMT : GMT时区是格林威治时间
UTC(Universal Coordinated Time) : UTC时区是根据GMT得来的“世界标准时间”
CST : CST时区指代有多个

1
2
3
4
澳洲中部时间,Central Standard Time (Australia)
中部标准时区(北美洲),Central Standard Time (North America)
北京时间,China Standard Time
古巴标准时间,Cuba Standard Time

我们所在的时区(东八区),按照北京时间,实际上CST=UTC +08:00

ISO 8601和UTC

UTC

用python分别输出 UTC 时区和CST(北京时区)的当前时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from datetime import datetime
# import pytz

# 默认时区(CST北京时区)
now_cst = datetime.now()
print(now_cst)

# 指定UTC时间
# utc_tz = pytz.timezone('UTC')
# now_utc = datetime.now(tz=utc_tz)
now_utc = datetime.utcnow()
print(now_utc)

# 输出结果
2020-07-01 14:08:49.946031
2020-07-01 06:08:49.946031

可以看到当前时区(北京)时间是UTC时间加8小时

ISO8601

ISO8601全称:数据存储和交换形式·信息交换·日期和时间的表示方法,是国际标准化组织制定的表示日期和时间的国际标准,官方原话:

1
This ISO standard helps remove doubts that can result from the various day–date conventions, cultures and time zones that impact a global operation. It gives a way of presenting dates and times that is clearly defined and understandable to both people and machines.

python将当前时间转换为 ISO8601格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from datetime import datetime
# import pytz

# 默认时区(CST北京时区)
now_cst = datetime.now()
print(now_cst)
print(now_cst.isoformat())

print("=" * 30)

# 指定UTC时间
# utc_tz = pytz.timezone('UTC')
# now_utc = datetime.now(tz=utc_tz)
now_utc = datetime.utcnow()
print(now_utc)
print(now_utc.isoformat())

# 输出结果
2020-07-01 14:34:10.948195
2020-07-01T14:34:10.948195
==============================
2020-07-01 06:34:10.948195
2020-07-01T06:34:10.948195

ISO8601格式的输出结果比普通输出结果多了一个T,T表示后面是日期时间值的时间部分;

除了这个区别,还有就是类型上的区别:

1
2
3
4
5
6
7
now_cst = datetime.now()
print(now_cst, type(now_cst))
print(now_cst.isoformat(), type(now_cst.isoformat()))

# 输出结果
2020-07-01 14:17:26.834861 <class 'datetime.datetime'>
2020-07-01T14:17:26.834861 <class 'str'>

可以看到将时间转换成ISO8601格式之后,类型也从datetime.datetime转换成了str

文章目录
  1. 时区
  2. ISO 8601和UTC
    1. UTC
    2. ISO8601
|