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.
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.
If you just want strings, you could remove the trailing seconds with a regex ':\d\d$' .
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With