time and datetime in Python and Go
Concepts
UTC vs GMT:
GMT:Greenwich Mean Time,指格林尼治標(biāo)準(zhǔn)時(shí)間蛾狗,這個(gè)時(shí)間是英國(guó)格林尼治天文臺(tái)根據(jù)觀測(cè)結(jié)果得出的時(shí)間扫步,在過(guò)去這個(gè)地方的時(shí)間被當(dāng)做世界標(biāo)準(zhǔn)時(shí)間致盟。
UT:Universal Time 世界時(shí)薪前,根據(jù)原子鐘計(jì)算出來(lái)的時(shí)間
UTC:Coordinated Universal Time 協(xié)調(diào)世界時(shí)贝乎。因?yàn)榈厍蜃詡髟絹?lái)越慢宋光,自傳一周每年都慢零點(diǎn)幾秒貌矿,因此每個(gè)幾年UTC都會(huì)給世界時(shí)+1秒,這個(gè)時(shí)間稱(chēng)為UTC罪佳。
UTC沒(méi)有時(shí)區(qū)的概念逛漫,GMT才有時(shí)區(qū)的概念。GMT=UTC+0, 北京時(shí)區(qū)=UTC + 8
不同的時(shí)間格式
最終要通過(guò)文本來(lái)表示時(shí)間赘艳,這里的時(shí)間包含如下元素:(年月日)+(時(shí)分秒)+ 毫秒 + 時(shí)區(qū)酌毡。時(shí)間格式定義了文本如何表示上述元素。常見(jiàn)的有isoformat蕾管。
本地時(shí)間和UTC時(shí)間:
- Timestamp, 即從UTC(1970.1.1 00:00:00) 的偏移量枷踏,time.time()
- localtime, time.struct_time() 用9 個(gè)成員表示年月日等信息, time.localtime()
- localtime, datetime.datetime() 類(lèi)似 2,表示年月日等信息掰曾,datetime.datetime.now()
時(shí)間有兩種表示方式旭蠕,一個(gè)是 UTC 時(shí)間,這個(gè)時(shí)間即 timestamp,與時(shí)區(qū)無(wú)關(guān)掏熬。二是本地時(shí)間佑稠,本地時(shí)間有時(shí)區(qū)的概念,因此又稱(chēng)為本地時(shí)間孽江。
常用的操作
format time string
請(qǐng)注意只能格式化本地時(shí)間讶坯,UTC 時(shí)間是沒(méi)有格式化的概念的
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
時(shí)間的加減
只能通過(guò) timedelta 來(lái)操作
datetime.datetime.now() - datetime.timedelta(days = 7)
python isoformat與go互轉(zhuǎn)
# python generate iso format time string
datetime.datetime.now().isoformat()
'2022-01-26T15:04:44.398239'
python isoformat打印iso格式的本地時(shí)間番电,請(qǐng)注意這個(gè)格式嚴(yán)格來(lái)說(shuō)與iso format標(biāo)準(zhǔn)不一致岗屏,按照標(biāo)準(zhǔn)字符串后面有一個(gè)'Z'字母表示UTC時(shí)間,Z means Zulu or Zero offset.
引用一段stackoverflow上關(guān)于為什么沒(méi)有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字符串轉(zhuǎn)為go time的方法
s := '2022-01-26T15:04:44.398239' // the text generated by python datetime.datetime.now().isoformat()
time.Parse(time.RFC3339, s + "Z")