Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python start date_range from a specific hour

I am trying to specify a date range in Python that begins on the day before the current day. However, I would like that date range to begin at 10:00:00.

This is the code I am currently using

import pandas as pd
import datetime as dt
date = dt.datetime.today() - dt.timedelta(days=1)
date_range = pd.date_range(date, freq='60min', periods=24)

However, this begins at 00:00:00. I have tried a few ways of amending the above code to get it to start at 10:00:00, but none work. Can anyone help?

To clarify: I am using Pandas because this date range is to be used as the index for a dataframe.

like image 514
pottolom Avatar asked Feb 05 '23 15:02

pottolom


2 Answers

You can construct another datetime but use just the day, month, year components and offset again:

In [87]:
date = dt.datetime.today() - dt.timedelta(days=1)
date = dt.datetime(date.year, date.month, date.day) + dt.timedelta(hours=10)
date_range = pd.date_range(date, freq='60min', periods=24)
date_range

Out[87]:
DatetimeIndex(['2016-11-22 10:00:00', '2016-11-22 11:00:00',
               '2016-11-22 12:00:00', '2016-11-22 13:00:00',
               '2016-11-22 14:00:00', '2016-11-22 15:00:00',
               '2016-11-22 16:00:00', '2016-11-22 17:00:00',
               '2016-11-22 18:00:00', '2016-11-22 19:00:00',
               '2016-11-22 20:00:00', '2016-11-22 21:00:00',
               '2016-11-22 22:00:00', '2016-11-22 23:00:00',
               '2016-11-23 00:00:00', '2016-11-23 01:00:00',
               '2016-11-23 02:00:00', '2016-11-23 03:00:00',
               '2016-11-23 04:00:00', '2016-11-23 05:00:00',
               '2016-11-23 06:00:00', '2016-11-23 07:00:00',
               '2016-11-23 08:00:00', '2016-11-23 09:00:00'],
              dtype='datetime64[ns]', freq='60T')
like image 100
EdChum Avatar answered Feb 08 '23 06:02

EdChum


try

today = pd.datetime.today().date()
today - pd.offsets.Hour(14)

Timestamp('2016-11-22 10:00:00')

Then use pd.date_range

pd.date_range(today - pd.offsets.Hour(14), periods=24, freq='H')

DatetimeIndex(['2016-11-22 10:00:00', '2016-11-22 11:00:00',
               '2016-11-22 12:00:00', '2016-11-22 13:00:00',
               '2016-11-22 14:00:00', '2016-11-22 15:00:00',
               '2016-11-22 16:00:00', '2016-11-22 17:00:00',
               '2016-11-22 18:00:00', '2016-11-22 19:00:00',
               '2016-11-22 20:00:00', '2016-11-22 21:00:00',
               '2016-11-22 22:00:00', '2016-11-22 23:00:00',
               '2016-11-23 00:00:00', '2016-11-23 01:00:00',
               '2016-11-23 02:00:00', '2016-11-23 03:00:00',
               '2016-11-23 04:00:00', '2016-11-23 05:00:00',
               '2016-11-23 06:00:00', '2016-11-23 07:00:00',
               '2016-11-23 08:00:00', '2016-11-23 09:00:00'],
              dtype='datetime64[ns]', freq='H')
like image 42
piRSquared Avatar answered Feb 08 '23 06:02

piRSquared