假设我有两个约会。 如何获得两个日期之间的所有中间日期和小时(从00到23)? 非常感谢你!
from datetime import datetime,timedelta, date
date_min = (datetime.today()-timedelta(1)).strftime('%Y-%m-%d')+' 00'
date_max = datetime.today().strftime('%Y-%m-%d')+' 00'
date_min, date_max
('2018-09-16 00', '2018-09-17 00')
how to obtain?
'2018-09-16 01', '2018-09-16 02', '2018-09-16 03', '2018-09-16 04', .... , '2018-09-16 21', '2018-09-16 22', '2018-09-16 23', '2018-09-17 00'
答案 0 :(得分:4)
使用大熊猫,它是一种衬套:
pandas timestamp
如果您想从datetime
转换回[timestamp.to_pydatetime() for timestamp in solution]
[datetime.datetime(2018, 9, 16, 0, 0), datetime.datetime(2018, 9, 16, 1, 0), datetime.datetime(2018, 9, 16, 2, 0), datetime.datetime(2018, 9, 16, 3, 0), datetime.datetime(2018, 9, 16, 4, 0), datetime.datetime(2018, 9, 16, 5, 0), datetime.datetime(2018, 9, 16, 6, 0), datetime.datetime(2018, 9, 16, 7, 0), datetime.datetime(2018, 9, 16, 8, 0), datetime.datetime(2018, 9, 16, 9, 0), datetime.datetime(2018, 9, 16, 10, 0), datetime.datetime(2018, 9, 16, 11, 0), datetime.datetime(2018, 9, 16, 12, 0), datetime.datetime(2018, 9, 16, 13, 0), datetime.datetime(2018, 9, 16, 14, 0), datetime.datetime(2018, 9, 16, 15, 0), datetime.datetime(2018, 9, 16, 16, 0), datetime.datetime(2018, 9, 16, 17, 0), datetime.datetime(2018, 9, 16, 18, 0), datetime.datetime(2018, 9, 16, 19, 0), datetime.datetime(2018, 9, 16, 20, 0), datetime.datetime(2018, 9, 16, 21, 0), datetime.datetime(2018, 9, 16, 22, 0), datetime.datetime(2018, 9, 16, 23, 0), datetime.datetime(2018, 9, 17, 0, 0)]
,请执行以下操作:
[timestamp.to_pydatetime().strftime('%Y-%m-%d %H') for timestamp in solution]
['2018-09-16 00', '2018-09-16 01', '2018-09-16 02', '2018-09-16 03', '2018-09-16 04', '2018-09-16 05', '2018-09-16 06', '2018-09-16 07', '2018-09-16 08', '2018-09-16 09', '2018-09-16 10', '2018-09-16 11', '2018-09-16 12', '2018-09-16 13', '2018-09-16 14', '2018-09-16 15', '2018-09-16 16', '2018-09-16 17', '2018-09-16 18', '2018-09-16 19', '2018-09-16 20', '2018-09-16 21', '2018-09-16 22', '2018-09-16 23', '2018-09-17 00']
要转换为您提到的字符串格式:
<form name="chatform">
答案 1 :(得分:3)
这将起作用:
date = datetime.today()-timedelta(days=1)
while date < datetime.today():
date = date + timedelta(hours=1)
print date.strftime('%Y-%m-%d %H')
并提供以下输出:
2018-09-17 00
2018-09-17 01
2018-09-17 02
2018-09-17 03
2018-09-17 04
2018-09-17 05
2018-09-17 06
2018-09-17 07
2018-09-17 08
您还可以指定从几小时开始:
date = datetime.today().replace(hour=0, minute=0, second=0)-timedelta(days=1)
答案 2 :(得分:2)
纯Python:
import itertools
from datetime import datetime,timedelta
date_max = datetime.today()
date_min = date_max - timedelta(hours=2)
n_hours = (date_max - date_min).total_seconds() / 3600
[date_min + timedelta(hours=x) for x in itertools.takewhile(lambda h: h <= n_hours, itertools.count())]
返回
[datetime.datetime(2018, 9, 17, 14, 49, 42, 193664),
datetime.datetime(2018, 9, 17, 15, 49, 42, 193664),
datetime.datetime(2018, 9, 17, 16, 49, 42, 193664)]