I want to create a function that returns the difference between the two given time in hourly increments.

Asked 2 years ago, Updated 2 years ago, 31 views

When two hours (start, end) are given, the time difference is 3 hours.

import datetime

start = datetime (2021, 1, 1, 1, 10)
end = datetime (2021, 1, 1, 4, 0)

I would like to use this to create the following functions, but there is no solution to this, so I would like to ask you a question.

def INPUT (start, end):
    # I don't know what to do here.

# Desired result: I want to create a function that returns the time between start and end.
INPUT (start, end) --> [2021-01-0101:00:00, 2021-01-0102:00:00, 2021-01-0103:00:00, 2021-01-0104:00:00]

Let's assume that start and end are separated by time.
Professor, please.

python python3

2022-09-29 22:25

2 Answers

from datetime import datetime, timedelta

def INPUT (start, end):
    return [start+timedelta(hours=i)for i in range(end-start).seconds//3600+1)]

if__name__=='__main__':
    start = datetime (2021, 1, 1, 1, 10)
    end = datetime (2021, 1, 1, 4, 0)

    ret = INPUT (start, end)
    print([d.strftime("%F%T") for direct]

#
['2021-01-01 01:00:00', '2021-01-01 02:00:00', '2021-01-01 03:00:00', '2021-01-01 04:00:00']


2022-09-29 22:25

How about the following?

import datetime as dt
import pandas aspd

start = dt.datetime (2021, 1, 1, 1, 0)
end = dt.datetime (2021, 1, 1, 4, 0)
print(start,end)

# one-hour interval
date_list=pd.date_range(start=start, end=end, freq='H')
display(date_list)
print('Type:', isinstance(date_list[0], dt.datetime))

◇ Output
2021-01-01:00:00 2021-01-0104:00
DatetimeIndex('2021-01-0101:00','2021-01-0102:00',
'2021-01-0103:00', '2021-01-0104:00'',
dtype='datetime64[ns]', freq='H')
Type: True


2022-09-29 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.