Python按天实现生成时间范围序列的方法详解
ponponon 人气:0有的时候我们希望生成一段时间返回,比如从 2022-01-01 00:00:00 后面的 10 天,这么 10 个 datetime 对象,但是我们又不想自己去计算哪些月有30天哪些月有31天。
使用 timedelta
datetime 中包含了 timedelta ,可以用来实现这个功能
from datetime import datetime, timedelta, timezone from pydantic.datetime_parse import parse_datetime from loguru import logger SECOND: int = 1 MINUTE: int = SECOND*60 HOUR: int = MINUTE*60 DAY: int = HOUR*24 WEEK: int = DAY*7 MONTH: int = DAY*30 def get_utc_now_timestamp(with_tzinfo: bool = True) -> datetime: """ https://blog.csdn.net/ball4022/article/details/101670024 """ if not with_tzinfo: return datetime.utcnow() return datetime.utcnow().replace(tzinfo=timezone.utc) def timedelta_seconds(start_time: datetime, end_time: datetime = None) -> int: """ 返回两个时间相差的秒数 """ if not end_time: end_time = get_utc_now_timestamp() return int((end_time - start_time).total_seconds()) def custom_timestamp(base_timestamp: datetime, seconds: int, reduce=False): return base_timestamp + timedelta(seconds=seconds) \ if not reduce \ else base_timestamp - timedelta(seconds=seconds) start_datetime = parse_datetime('2022-02-27 00:00:00') data = [ dt for dt in [ custom_timestamp(start_datetime, DAY*i) for i in range(10) ] ] logger.debug(data)
输出如下:
╰─➤ python -u "/Users/ponponon/Desktop/code/me/ideaboom/main.py"
2022-11-15 15:18:37.653 | DEBUG | __main__:<module>:67 - [datetime.datetime(2022, 2, 27, 0, 0), datetime.datetime(2022, 2, 28, 0, 0), datetime.datetime(2022, 3, 1, 0, 0), datetime.datetime(2022, 3, 2, 0, 0), datetime.datetime(2022, 3, 3, 0, 0), datetime.datetime(2022, 3, 4, 0, 0), datetime.datetime(2022, 3, 5, 0, 0), datetime.datetime(2022, 3, 6, 0, 0), datetime.datetime(2022, 3, 7, 0, 0), datetime.datetime(2022, 3, 8, 0, 0)]
使用 arrow 这个第三方库
import arrow from loguru import logger from pydantic.datetime_parse import parse_datetime for crawl_date in arrow.Arrow.range('day', parse_datetime('2022-02-27 00:00:00'), parse_datetime('2022-03-10 00:00:00')): logger.debug(crawl_date.datetime)
输出如下:
╰─➤ python -u "/Users/ponponon/Desktop/code/me/ideaboom/datetime_arrow_range.py"
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-02-27 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-02-28 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-01 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-02 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-03 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-04 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-05 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-06 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-07 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-08 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-09 00:00:00+00:00
2022-11-15 15:28:52.130 | DEBUG | __main__:<module>:6 - 2022-03-10 00:00:00+00:00
补充
当然,Python还有很多生成不同要求的时间序列的方法,下面小编为大家整理了一些,希望对大家有所帮助
生成不同间隔的时间序列
import pandas as pd import numpy as np import datetime as dt # 从2022-07-01开始,间隔3天,生成10条 时间数据 rng = pd.date_range('2022-07-01', periods = 10, freq = '3D') print(rng) print("#####################") # 指定开始时间,结束时间 以及频率 data=pd.date_range('2022-01-01','2023-01-01',freq='M') print(data) print("#####################") # 从2022-01-01开始,间隔1天,生成20条 时间数据 time=pd.Series(np.random.randn(20), index=pd.date_range(dt.datetime(2022,1,1),periods=20)) print(time) print("#####################") # 不规则的时间间隔 p1 = pd.period_range('2022-01-01 10:10', freq = '25H', periods = 10) print(p1) print("######################################") # 指定索引 rng = pd.date_range('2022 Jul 1', periods = 10, freq = 'D') print(pd.Series(range(len(rng)), index = rng)) print("######################################")
测试记录:
DatetimeIndex(['2022-07-01', '2022-07-04', '2022-07-07', '2022-07-10',
'2022-07-13', '2022-07-16', '2022-07-19', '2022-07-22',
'2022-07-25', '2022-07-28'],
dtype='datetime64[ns]', freq='3D')
#####################
DatetimeIndex(['2022-01-31', '2022-02-28', '2022-03-31', '2022-04-30',
'2022-05-31', '2022-06-30', '2022-07-31', '2022-08-31',
'2022-09-30', '2022-10-31', '2022-11-30', '2022-12-31'],
dtype='datetime64[ns]', freq='M')
#####################
2022-01-01 -0.957412
2022-01-02 -0.333720
2022-01-03 1.079960
2022-01-04 0.050675
2022-01-05 0.270313
2022-01-06 -0.222715
2022-01-07 -0.560258
2022-01-08 1.009430
2022-01-09 -0.678157
2022-01-10 0.213557
2022-01-11 -0.720791
2022-01-12 0.332096
2022-01-13 -0.986449
2022-01-14 -0.357303
2022-01-15 -0.559618
2022-01-16 0.480281
2022-01-17 -0.443998
2022-01-18 1.541631
2022-01-19 -0.094559
2022-01-20 1.875012
Freq: D, dtype: float64
#####################
PeriodIndex(['2022-01-01 10:00', '2022-01-02 11:00', '2022-01-03 12:00',
'2022-01-04 13:00', '2022-01-05 14:00', '2022-01-06 15:00',
'2022-01-07 16:00', '2022-01-08 17:00', '2022-01-09 18:00',
'2022-01-10 19:00'],
dtype='period[25H]', freq='25H')
######################################
2022-07-01 0
2022-07-02 1
2022-07-03 2
2022-07-04 3
2022-07-05 4
2022-07-06 5
2022-07-07 6
2022-07-08 7
2022-07-09 8
2022-07-10 9
Freq: D, dtype: int64
######################################
截断时间段
import pandas as pd import numpy as np import datetime as dt # 从2022-01-01开始,间隔1天,生成20条 时间数据 time=pd.Series(np.random.randn(20), index=pd.date_range(dt.datetime(2022,1,1),periods=20)) print(time) print("#####################") # 只输出2022-01-10 之后的数据 print(time.truncate(before='2022-1-10')) print("#####################") # 只输出2022-01-10 之后的数据 print(time.truncate(after='2022-1-10')) print("#####################") # 输出区间段 print(time['2022-01-15':'2022-01-20']) print("#####################")
测试记录:
2022-01-01 -0.203552
2022-01-02 -1.035483
2022-01-03 0.252587
2022-01-04 -1.046993
2022-01-05 0.152435
2022-01-06 -0.534518
2022-01-07 0.770170
2022-01-08 -0.038129
2022-01-09 0.531485
2022-01-10 0.499937
2022-01-11 0.815295
2022-01-12 2.315740
2022-01-13 -0.443379
2022-01-14 -0.689247
2022-01-15 0.667250
2022-01-16 -2.067246
2022-01-17 -0.105151
2022-01-18 -0.420562
2022-01-19 1.012943
2022-01-20 0.509710
Freq: D, dtype: float64
#####################
2022-01-10 0.499937
2022-01-11 0.815295
2022-01-12 2.315740
2022-01-13 -0.443379
2022-01-14 -0.689247
2022-01-15 0.667250
2022-01-16 -2.067246
2022-01-17 -0.105151
2022-01-18 -0.420562
2022-01-19 1.012943
2022-01-20 0.509710
Freq: D, dtype: float64
#####################
2022-01-01 -0.203552
2022-01-02 -1.035483
2022-01-03 0.252587
2022-01-04 -1.046993
2022-01-05 0.152435
2022-01-06 -0.534518
2022-01-07 0.770170
2022-01-08 -0.038129
2022-01-09 0.531485
2022-01-10 0.499937
Freq: D, dtype: float64
#####################
2022-01-15 0.667250
2022-01-16 -2.067246
2022-01-17 -0.105151
2022-01-18 -0.420562
2022-01-19 1.012943
2022-01-20 0.509710
Freq: D, dtype: float64
#####################
加载全部内容