title: 技巧25: 批量随机生成时间戳 date: 2024-11-28
技巧25: 批量随机生成时间戳
实现方法
如下批量生成时间戳,random_timestamp
函数中,hour
传入小时(24小时制)
ymd
表示年月日,默认为2021-12-01
import random
import pandas as pd
def random_timestamp(hour, ymd='2021-12-01'):
"""
生成年月日固定,分秒随机的时间戳
:param ymd:
:param hour: 传入小时
:return:
"""
def tstr():
tms = set([random.randrange(1, 59, 2) for _ in range(20)])
return [f'2020-12-01 {hour}:{ms}:{ms}' for ms in tms]
return [pd.Timestamp(ws) for ws in tstr()]
调用
series = random_timestamp(9)
[Timestamp('2020-12-01 09:01:01'), Timestamp('2020-12-01 09:35:35'), Timestamp('2020-12-01 09:05:05'), Timestamp('2020-12-01 09:07:07'), Timestamp('2020-12-01 09:09:09'), Timestamp('2020-12-01 09:11:11'), Timestamp('2020-12-01 09:13:13'), Timestamp('2020-12-01 09:19:19'), Timestamp('2020-12-01 09:53:53'), Timestamp('2020-12-01 09:55:55'), Timestamp('2020-12-01 09:23:23'), Timestamp('2020-12-01 09:21:21'), Timestamp('2020-12-01 09:29:29'), Timestamp('2020-12-01 09:31:31')]