Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python datetime remove minute and second information

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.

like image 655
Zanam Avatar asked Jul 13 '16 18:07

Zanam


People also ask

How do I get rid of hours minutes and seconds in datetime in Python?

Using strfttime to Remove the Time from Datetime in Python We can use strftime() to easily remove the time from datetime variables. For example, if you want to print out the date in the format “YYYY-MM-DD”, we pass “%Y-%m-%d” to strfttime() and no time is printed.

How do I remove the seconds from a datetime column in Python?

If you just want strings, you could remove the trailing seconds with a regex ':\d\d$' .

How do I remove seconds from datetime?

This is by design. If you don't want to display the seconds when you create the string, use a format string, like MM/dd/yyyy hh.mm and leave the tt part off.


2 Answers

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)
like image 58
Kevin M Granger Avatar answered Oct 05 '22 23:10

Kevin M Granger


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)
like image 43
Psidom Avatar answered Oct 06 '22 00:10

Psidom