22

I have a datetime array which has hour, minute and second information. I want to remove the minute and second infromation from it and change the hour to the next hour.

i.e. peak_interval

array([datetime.datetime(2010, 12, 13, 6, 0),
       datetime.datetime(2011, 1, 12, 7, 0),
       datetime.datetime(2011, 3, 23, 16, 45),
       datetime.datetime(2011, 4, 19, 17, 15)], dtype=object)

I want to obtain the following:

peak_interval
array([datetime.datetime(2010, 12, 13, 7, 0),
       datetime.datetime(2011, 1, 12, 8, 0),
       datetime.datetime(2011, 3, 23, 17, 0),
       datetime.datetime(2011, 4, 19, 18, 0)], dtype=object)

I can write some kind of for loop but I am trying to use some smart method if possible.

Zanam
  • 4,607
  • 13
  • 67
  • 143
  • This may help you: http://stackoverflow.com/questions/3743222/how-do-i-convert-datetime-to-date-in-python Keep in mind, though, that the result in that case would be a date object. – Haroldo_OK Jul 13 '16 at 18:51

3 Answers3

40

You can easily modify just a few fields using datetime.datetime.replace

old_date = datetime.datetime(2011, 3, 23, 16, 45)
new_date = old_date.replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=1)
otmezger
  • 10,410
  • 21
  • 64
  • 90
Kevin M Granger
  • 2,375
  • 23
  • 28
  • Hi @KevinMGranger, it's replacing `minutes`, and `seconds` with `0`, can we completely remove this information from datetime? – Abdul Rehman Jun 23 '19 at 07:41
  • 1
    @AbdulRehman a `datetime` by definition has a `date` and a `time`. If you don't want time information, use a `date`. You can convert a `datetime` by calling `datetime.date()`. – Kevin M Granger Jun 24 '19 at 15:44
3

One option is to use timedelta from datetime:

import datetime
import numpy as np
def reset(dt):
    return dt + datetime.timedelta(hours = 1, minutes = -dt.minute, seconds = -dt.second)

np.vectorize(reset)(peak_interval)

# array([datetime.datetime(2010, 12, 13, 7, 0),
#        datetime.datetime(2011, 1, 12, 8, 0),
#        datetime.datetime(2011, 3, 23, 17, 0),
#        datetime.datetime(2011, 4, 19, 18, 0)], dtype=object)
Psidom
  • 209,562
  • 33
  • 339
  • 356
3
now = datetime.now()
now2 = datetime(now.year,now.month,now.day,now.hour)