1. 程式人生 > 實用技巧 >python datetime 和 time 模組總結

python datetime 和 time 模組總結

time

# 時間戳
time.time()    

# 返回 time.struct_time 元組
time.localtime()    # time.struct_time(tm_year=2020, tm_mon=12, tm_mday=29, tm_hour=14, tm_min=38, tm_sec=24, tm_wday=1, tm_yday=364, tm_isdst=0)

# time.struct_time 元組轉換為時間戳
time.mktime(struct_time)    # 傳入一個 struct_time 元組

# 時間字串---》 time.struct_time 元組
time.strptime('2020-02-02', '%Y-%m-%d')

# struct_time元組---》 時間字串
time.strftime("%Y-%m-%d")    # 2020-12-29 14:44:53

time 轉換

# 時間戳 ---》 時間  1452646860 -- 2016-01-13
1. time.strftime("%Y-%m-%d", time.localtime(1452646860))
2. pd.to_datetime(int(time.time()) + 28800, unit='s')

# 時間戳 ---》 時間  1609229819 -- 20201229
time.strftime('%Y%m%d', time.localtime(time.time()))

# 時間字串 ---》 時間戳 2020-02-02 -- 1580572800
time.mktime(time.strptime('2020-02-02', '%Y-%m-%d'))

# 時間字串 ---》 時間戳  20200202 -- 1580572800
time.mktime(time.strptime('20200202', '%Y%m%d'))

datetime

# datetime.date類

datetime.date.today()    # 2020-12-29    datetime.date 型別

datetime.date(2020, 2, 2)    # 2020-02-02    datetime.date 型別

datetime.date.today().timetuple()    # time.struct_time 元組

datetime.date.today().isoweekday()    # 返回今天星期,星期一是 1

datetime.date.today().isoformat()    # 返回時間字串 2020-12-29

datetime.date.today().strftime('%Y%m%d')    # 返回字串  20201229

# datetime.datetime 類
datetime.datetime.strptime('20200202', '%Y%m%d')    # 2020-02-02  <class 'datetime.datetime'> 型別

print(datetime.datetime.now().strftime('%Y%m%d'))    # 20201229

datetime 轉換

unix時間戳轉化為當前時間    datetime.datetime.fromtimestamp(1588834800.0)
把時間轉換成unix時間戳      datetime.datetime.strptime(str(context.start_minute), "%Y%m%d%H%M%S").timestamp()


import time
import datetime
import pandas as pd

# 時間字串轉換成時間戳
a1 = "2019-5-10 23:40:00"
# 先轉換為時間陣列
timeArray = time.strptime(a1, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(time.strptime(a1, "%Y-%m-%d %H:%M:%S")))
print(timeStamp)        1557502800


# 字串轉換成時間戳
d = '201703270000'
sss = time.mktime(datetime.datetime.strptime(d, "%Y%m%d%H%M%S").timetuple())
print(sss)       1490544000.0


# 時間戳轉換成時間字串
dd = 1490544000.0
dt = pd.to_datetime(dd, unit='s')
print(dt)       2017-03-26 16:00:00    # 時間是格林尼治時間,與北京時間相差8小時
        
print(datetime.datetime.strptime('201703302359', "%Y%m%d%H%M"))    # 2017-03-30 23:59:00

# 獲取前一天的時間
now = datetime.datetime.now()    # 2020-06-09 11:26:02.823512
before = (now + datetime.timedelta(days=-1)).strftime('%Y%m%d') + '210000'
print(before)    # 20200608210000
time.mktime(datetime.datetime.strptime(before, "%Y%m%d%H%M%S").timetuple())# 1591621200.0

# 轉換成df物件
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')

# 將 "2019-5-10 23:40:00" 群轉成時間戳
df_data_resample.index.map(lambda x: time.mktime(time.strptime(str(x), "%Y-%m-%d %H:%M:%S")))