Python生成日期系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4479800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:55:08  来源:igfitidea点击:

Python generate dates series

pythondatetimetimestamp

提问by Rafa? Kot

How can i generate array with dates like this:

我怎样才能用这样的日期生成数组:

Timestamps in javascript miliseconds format from 2010.12.01 00:00:00 to 2010.12.12.30 23.59.59 with step 5 minutes.

javascript 毫秒格式的时间戳,从 2010.12.01 00:00:00 到 2010.12.12.30 23.59.59,步长为 5 分钟。

['2010.12.01 00:00:00', '2010.12.01 00:05:00','2010.12.01 00:10:00','2010.12.01 00:15:00', ...]

采纳答案by Lennart Regebro

Well, obviously you start at the start time, loop until you reach the end time and increment inbetween.

好吧,显然你从开始时间开始,循环直到你到达结束时间并在中间增加。

import datetime

dt = datetime.datetime(2010, 12, 1)
end = datetime.datetime(2010, 12, 30, 23, 59, 59)
step = datetime.timedelta(seconds=5)

result = []

while dt < end:
    result.append(dt.strftime('%Y-%m-%d %H:%M:%S'))
    dt += step

Fairly trivial.

相当琐碎。

回答by cgi

this is my variant for python3, but it's easy could be converted into python2.6 code:

这是我的python3变体,但很容易转换成python2.6代码:

import datetime as dt

dt1 = dt.datetime(2010, 12, 1)
dt2 = dt.datetime(2010, 12, 12, 23, 59, 59)

time_step = 5 # secoonds
delta = dt2 - dt1

delta_sec = delta.days * 24 * 60 * 60 + delta.seconds

res = [dt1 + dt.timedelta(0, t) for t in range(0, delta_sec, time_step)]

回答by cantdutchthis

I just felt that it might be worthwhile to note that pandasalso has this functionality. Depending on what case you are dealing with exactly, pandas might be a worthy tool to invest time in.

我只是觉得它pandas也有这个功能可能值得一提。根据您具体处理的情况,pandas 可能是一个值得投入时间的工具。

import pandas as pd 
times = pd.date_range('2012-10-01', periods=289, freq='5min')

This returns a pandas timeseries-index. Which can be converted to numpy arrays.

这将返回一个熊猫时间序列索引。可以转换为 numpy 数组。

np.array(times)