[英]How to generate new hourly timestamps of future in python?
I am writing this code to create a current timestamp:我正在编写此代码以创建当前时间戳:
datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
This gives the following output:这给出了以下 output:
'2020-07-02 01:00:00'
I want to generate all 24 hours of timestamp for a particular day, something like:我想为特定的一天生成所有 24 小时的时间戳,例如:
'2020-07-02 00:00:00'
'2020-07-02 01:00:00'
'2020-07-02 02:00:00'
'2020-07-02 03:00:00'
'2020-07-02 04:00:00'
'2020-07-02 05:00:00'
'2020-07-02 06:00:00'
.
.
.
'2020-07-02 22:00:00'
'2020-07-02 23:00:00'
One idea I have in mind, is to copy the date 24 times and create a string like 00:00:00
and then use some logic to increment it by one until 23:00:00
and then concatenate dates and these strings and then convert it into datetime object.我想到的一个想法是复制日期 24 次并创建一个像
00:00:00
这样的字符串,然后使用一些逻辑将其递增 1 直到23:00:00
,然后连接日期和这些字符串,然后转换它进入日期时间 object。
However, this seems like a lot of work if I want to do if its for 10 days that is 240 hours and 10 different dates in future.但是,如果我想做 10 天,即 240 小时和 10 个不同的未来日期,这似乎需要做很多工作。
Is there a logic that you can suggest to achieve future timestamps for all 24 hours (no minutes, no seconds) for however many days I require?无论我需要多少天,您是否可以建议实现所有 24 小时(无分钟,无秒)的未来时间戳的逻辑?
Something like:就像是:
number_of days = input('How many days timestamps do you need?')
my_timestamp_function(number_of_days):
some_logic_using_the_number_of_days
return pd.Series(output)
Thank you, Viphawee谢谢你,维帕威
you can use datetime.timedelta(hours=1)
你可以使用
datetime.timedelta(hours=1)
def generate_datetimes(date_from_str='2020-01-01', days=3):
date_from = datetime.datetime.strptime(date_from_str, '%Y-%m-%d')
for hour in range(24*days):
yield date_from + datetime.timedelta(hours=hour)
for date in generate_datetime():
print(date.strftime('%Y-%m-%d %H:%M:%S'))
and you will get你会得到
2020-01-01 00:00:00
2020-01-01 01:00:00
2020-01-01 02:00:00
...
2020-01-03 22:00:00
2020-01-03 23:00:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.