python datetime

time and datetime in Python and Go

Concepts

UTC vs GMT:

GMT:Greenwich Mean Time,指格林尼治标准时间,这个时间是英国格林尼治天文台根据观测结果得出的时间,在过去这个地方的时间被当做世界标准时间。
UT:Universal Time 世界时,根据原子钟计算出来的时间
UTC:Coordinated Universal Time 协调世界时。因为地球自传越来越慢,自传一周每年都慢零点几秒,因此每个几年UTC都会给世界时+1秒,这个时间称为UTC。

UTC没有时区的概念,GMT才有时区的概念。GMT=UTC+0, 北京时区=UTC + 8

不同的时间格式

最终要通过文本来表示时间,这里的时间包含如下元素:(年月日)+(时分秒)+ 毫秒 + 时区。时间格式定义了文本如何表示上述元素。常见的有isoformat

本地时间和UTC时间:

  1. Timestamp, 即从UTC(1970.1.1 00:00:00) 的偏移量,time.time()
  2. localtime, time.struct_time() 用9 个成员表示年月日等信息, time.localtime()
  3. localtime, datetime.datetime() 类似 2,表示年月日等信息,datetime.datetime.now()

时间有两种表示方式,一个是 UTC 时间,这个时间即 timestamp,与时区无关。二是本地时间,本地时间有时区的概念,因此又称为本地时间。

常用的操作

format time string

请注意只能格式化本地时间,UTC 时间是没有格式化的概念的

time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

时间的加减

只能通过 timedelta 来操作

datetime.datetime.now() - datetime.timedelta(days = 7)

python isoformat与go互转

# python generate iso format time string
datetime.datetime.now().isoformat()
'2022-01-26T15:04:44.398239'

python isoformat打印iso格式的本地时间,请注意这个格式严格来说与iso format标准不一致,按照标准字符串后面有一个'Z'字母表示UTC时间,Z means Zulu or Zero offset.
引用一段stackoverflow上关于为什么没有Z的回答

Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself

// python isoformat字符串转为go time的方法
s := '2022-01-26T15:04:44.398239' // the text generated by python datetime.datetime.now().isoformat()
time.Parse(time.RFC3339, s + "Z")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容