pandas中的时间操作

时间生成

生成当前时间

使用 pandas 获取当前时间

import pandas as pd

pd.Timestamp('now')
Timestamp('2021-12-06 11:16:01.418830')

生成指定时间范围

使用 pandas 按天生成 2021年1月1日2021年9月1日 的全部日期

pd.date_range('1/1/2021','9/11/2021')
DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
               '2021-01-09', '2021-01-10',
               ...
               '2021-09-02', '2021-09-03', '2021-09-04', '2021-09-05',
               '2021-09-06', '2021-09-07', '2021-09-08', '2021-09-09',
               '2021-09-10', '2021-09-11'],
              dtype='datetime64[ns]', length=254, freq='D')

生成指定间隔时间

使用 pandas2021年1月1日 开始,按天生成 10 天日期

pd.date_range("2021-01-01", periods=10)
DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
               '2021-01-09', '2021-01-10'],
              dtype='datetime64[ns]', freq='D')

生成指定频率时间

使用 pandas 从 2021年1月1日开始,按周生成 7 周日期

pd.date_range("2021-01-01", periods=7, freq="W")
DatetimeIndex(['2021-01-03', '2021-01-10', '2021-01-17', '2021-01-24',
               '2021-01-31', '2021-02-07', '2021-02-14'],
              dtype='datetime64[ns]', freq='W-SUN')

生成工作日时间

使用 pandas 按天生成 2021年1月1日 至 2021年9月1日的全部工作日日期

pd.bdate_range(start='1/1/2021', end='9/1/2021')
DatetimeIndex(['2021-01-01', '2021-01-04', '2021-01-05', '2021-01-06',
               '2021-01-07', '2021-01-08', '2021-01-11', '2021-01-12',
               '2021-01-13', '2021-01-14',
               ...
               '2021-08-19', '2021-08-20', '2021-08-23', '2021-08-24',
               '2021-08-25', '2021-08-26', '2021-08-27', '2021-08-30',
               '2021-08-31', '2021-09-01'],
              dtype='datetime64[ns]', length=174, freq='B')

时间计算

计算时间差(天)

使用 pandas 计算 2021年2月14日 距离今天相差多少天

(pd.Timestamp('now') - pd.to_datetime('2021-02-14')).days
295

计算时间差(小时)

使用 pandas 计算 2021年9月1日13点14分 距离今天相差多少小时

import numpy as np
(pd.Timestamp('now') - pd.to_datetime('2021-09-01 13:14:00'))/np.timedelta64(1, 'h')
2302.083398611111

时间加减

将现在的时间减去一天,并格式化为 xx年xx月xx日 xx时xx分xx秒

(pd.Timestamp('now') - pd.to_timedelta('1 day'))
Timestamp('2021-12-05 11:18:59.153271')

时间格式化

将上一题的结果式化为 xx年xx月xx日-xx时xx分xx秒

(pd.Timestamp('now') - pd.to_timedelta('1 day')).strftime("%Y年%m月%d日-%H时%M分%S秒")
'2021年12月05日-11时19分14秒'