简体   繁体   English

使用python datetime在早上9点到晚上6点之间划分时间到3小时的时间间隔

[英]divide time between morning 9AM to evening 6PM in to 3hrs time interval using python datetime

Basically, what I am trying to do is, divide the time between morning 9 AM and evening 6 PM into specified time hours interval 基本上,我要做的是将早上9点到晚上6点之间的时间分成指定的时间间隔

For example, if I specify the time gap interval as 3 hours then I should get the result by dividing the time between 9 to 6 as 例如,如果我将时间间隔间隔指定为3小时,那么我应该通过将时间间隔在9到6之间来得到结果

['2017-05-03 09:00', '2017-05-03 12:00', '2017-05-03 15:00', '2017-05-03 18:00']

If I specify the time gap interval as 2 hours then I should get 如果我将时间间隔指定为2小时,那么我应该得到

['2017-05-03 09:00', '2017-05-03 11:00', '2017-05-03 13:00', '2017-05-03 15:00', '2017-05-03 17:00']

Below is my code for doing it 以下是我的代码

from datetime import datetime
from datetime import timedelta
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

result = []
time_interval = 3
while start_time <=end_time:
    result.append(start_time)
    start_time += timedelta(hours=time_interval)

print(result)

Basically, I used while in the above code to check condition, so is it possible to do the same above logic without using while statement and by using some other logic using list comprehension etc .,? 基本上,我在上面的代码中使用while来检查条件,所以是否可以在不使用while语句和使用其他逻辑使用列表理解等的情况下执行相同的上述逻辑。

Also if possible I need the output list as 如果可能的话,我还需要输出列表

[
'2017-05-03 09:00 to 2017-05-03 12:00', 
'2017-05-03 12:00 to 2017-05-03 15:00', 
'2017-05-03 15:00 to 2017-05-03 18:00'
]

Alternatively, you can solve the problem with rrule() from dateutil to generate the datetimes in a specified range hourly and then iterating over the results with a specified step : 或者,也可以解决该问题rrule()dateutil产生在一个指定范围内的日期时间每小时,然后遍历与指定结果step

from datetime import datetime
from datetime import timedelta
from itertools import islice

from dateutil.rrule import HOURLY, rrule

interval = 3
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

stops = islice(rrule(freq=HOURLY, dtstart=start_time, until=end_time), None, None, interval)
print([datetime.strftime(stop, "%Y-%d-%m %H:%M") for stop in stops])

Prints: 打印:

['2017-05-03 09:00', '2017-05-03 12:00', '2017-05-03 15:00', '2017-05-03 18:00']

Note that the list comprehension and the strftime() calls here are for demonstration purposes only - stops is an iterator that "contains" the desired datetimes . 请注意,列表strftime()和此处的strftime()调用仅用于演示目的 - stops是一个“包含”所需datetimes的迭代器。

And, applying the same pairwise helper as @NiL used, we can get to your next desired output: 并且,使用与使用的@NiL相同的pairwise助手,我们可以获得您的下一个所需输出:

from datetime import datetime
from datetime import timedelta
from itertools import islice, tee

from dateutil.rrule import HOURLY, rrule


def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...

    https://docs.python.org/2/library/itertools.html
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


interval = 3
start_time = datetime.now().replace(hour=9, minute=0) #(Morning 9 AM)
end_time = start_time + timedelta(hours=9) # (Evening 6 PM)

stops = islice(rrule(freq=HOURLY, dtstart=start_time, until=end_time), None, None, interval)

print(['{0} to {1}'.format(datetime.strftime(start, "%Y-%d-%m %H:%M"),
                           datetime.strftime(stop, "%Y-%d-%m %H:%M"))
       for start, stop in pairwise(stops)])

Prints: 打印:

['2017-03-05 09:00 to 2017-03-05 12:00', '2017-03-05 12:00 to 2017-03-05 15:00', '2017-03-05 15:00 to 2017-03-05 18:00']

something like this might do what you want 这样的事情可能会做你想要的

from datetime import datetime
from datetime import timedelta
from itertools import tee
start_time = datetime.now().replace(hour=9, minute=0)  # (Morning 9 AM)
end_time = start_time + timedelta(hours=9)  # (Evening 6 PM)

time_interval = 3
delta = 9  # hours


def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...

    https://docs.python.org/2/library/itertools.html
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


iterations = (delta // time_interval) + 1
result = [start_time+i*timedelta(hours=time_interval)
          for i in range(iterations)]
print(result)

formatted=['{} to {}'.format(
    start.strftime('%Y-%m-%d %H:%M'),
    end.strftime('%Y-%m-%d %H:%M'))
    for start, end in pairwise(result)]

from pprint import pprint
pprint(formatted)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Dataframe 时间拆分为早晚 - Splitting Dataframe time into morning and evening 使用 Python (pandas, datetime) 在 dataframe 中查找事件(具有开始和结束时间)是否超过特定时间(例如下午 6 点) - Find whether an event (with a start & end time) goes beyond a certain time (e.g. 6pm) in dataframe using Python (pandas, datetime) 当时间为0 -11小时时,我正在反过来得到答案。 - Am Getting Answer In Reverse, When Time Is 0 -11 Hrs It's Printing Good Evening 如何使用时间列创建包含一天中一部分时间的新列 [&#39;morning&#39; , &#39;afternoon&#39; , &#39;evening&#39;, &#39;night&#39; ] ? - How to create new column containing part of the day as ['morning' , 'afternoon' , 'evening', 'night' ] using time column? 将一列中所有时间条目的时间格式从小时更改为AM / PM - Change time formats of all time entries in a column from hrs to AM/PM 使用“时间”获取上午或下午 - Get AM or PM using 'time' 如何使用python将时间序列分成间隔(不等于间隔)和每个间隔的总和值 - How to divide the time series into intervals(not equal interval) and sum value in each interval using python 使用 time.strptime() 在 Python 中使用 AM/PM 解析日期时间字符串时出错 - Error while parsing a datetime string with AM/PM in Python with time.strptime() 使用 AM/PM 和 +UCT (Python) 转换时间 - Convert Time with AM/PM and +UCT (Python) 获取 DateTime 之间的时间间隔的平均值 - Get the average of Time interval between DateTime
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM