How to Extract Hours and Minutes from a Datetime.Datetime Object

How can I extract hours and minutes from a datetime.datetime object?

I don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

How do I extract the Hour/Minute from a datetime object and get rid of the Year/Month/Day/Second section?

You're converting back and forth into strings; instead, parse each of the times once, then keep them as times. Only convert them back to strings (if necessary) at the very end.

wed_start_in = input("What time did you start?") # asks starting time
wed_start = datetime.strptime(wed_start_in, "%H:%M") # converts time start input into a datetime object
wed_finish_in = input("And what time did you finish?") # asks finishing time
wed_finish = datetime.strptime(wed_finish_in, "%H:%M")
wed_hours = wed_finish - wed_start
print(wed_hours)

Extracting year, month, day, hour and minute from the current datetime

Just use now. And no parenths.

from datetime import datetime

now = datetime.now()

print(now.day)
print(now.month)
print(now.year)
print(now.hour)
print(now.minute)

How to extract hour:minute from a datetime stamp in Python

#rng = pd.date_range('1/5/2018 00:00', periods=5, freq='35T')
#df = pd.DataFrame({'POA':randint(1, 10, 5)}, index=rng)
labels = df.index.strftime('%H:%M')
x = np.arange(len(labels))
plt.plot(x, df['POA'])
plt.xticks(x, labels)

Steps:

  • labels = df.index.strftime('%H:%M') => Convert the datetime to "Hours:minutes" format to use as x labels
  • x = np.arange(len(labels)) => Create a dummy x axis for matplotlib
  • plt.plot(x, df['POA']) => Make the plot
  • plt.xticks(x, labels) => Replace the x labels with datetime

Assumption: The datetime index is sorted, if not the graph will be messed up. If the index is not in sorted order then sort it before plotting for correct results.

We can further enhance the x axis to include seconds, dates, etc by using the appropriate string formatter in df.index.strftime

Solution with skipping x-ticks to avoid clubbed x labels

#rng = pd.date_range('1/5/2018 00:00', periods=50, freq='35T')
#df = pd.DataFrame({'POA':randint(1, 10, 50)}, index=rng)
labels = df.index.strftime('%H:%M')
x = np.arange(len(labels))
fig, ax = plt.subplots()
plt.plot(x, df['POA'])
plt.xticks(x, labels)
skip_every_n = 10
for i, x_label in enumerate(ax.xaxis.get_ticklabels()):
if i % skip_every_n != 0:
x_label.set_visible(False)

Extraction of hour from datetime object in Pandas

Assuming this input:

s = pd.to_datetime(pd.Series(['00:10', '12:30', '23:35']))
0 2022-04-18 00:10:00
1 2022-04-18 12:30:00
2 2022-04-18 23:35:00
dtype: datetime64[ns]

hours

s.dt.hour
0 0
1 12
2 23
dtype: int64

An indeed, if you round:

s.dt.round('h').dt.hour
0 0
1 12
2 0
dtype: int64

what you can do it to convert rounded hour+minutes

s.dt.hour.add(s.dt.minute/60).round().astype(int)
0 0
1 12
2 24
dtype: int64

Extract hour and minutes from timestamp but keep it in datetime format

As Chris commented, it is not possible to convert just the hours and minutes into datetime format. But you can use timedeltas to solve your problem.

import datetime
import pandas as pd

def to_timedelta(date):
date = pd.to_datetime(date)
try:
date_start = datetime.datetime(date.year, date.month, date.day, 0, 0)
except TypeError:
return pd.NaT # to keep dtype of series; Alternative: pd.Timedelta(0)
return date - date_start


df['open'].apply(to_timedelta)

Output:

5        NaT
6 16:00:00
7 14:30:00
8 NaT
9 18:45:00
Name: open, dtype: timedelta64[ns]

Now you can use datetime.timedelta to add/subtract minutes, hours or whatever:

df['open'] + datetime.timedelta(minutes=15)

Output:

5        NaT
6 16:15:00
7 14:45:00
8 NaT
9 19:00:00
Name: open, dtype: timedelta64[ns]

Also, it is pretty easy to get back to full datetimes:

df['open'] + datetime.datetime(2020, 4, 4)

Output:

5                   NaT
6 2020-04-04 16:00:00
7 2020-04-04 14:30:00
8 NaT
9 2020-04-04 18:45:00
Name: open, dtype: datetime64[ns]

extract hour from timestamp with python

I think you need dt.hour:

print (df.TIMESTAMP.dt.hour)
0 0
1 0
Name: TIMESTAMP, dtype: int64

df['hours'] = df.TIMESTAMP.dt.hour
print (df)
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR hours
0 2016-01-01 00:00:00 116 HC 250 0
1 2016-01-01 00:10:00 121 HC 250 0

How to get current time in python and break up into year, month, day, hour, minute?

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don't need separate variables, the attributes on the returned datetime object have all you need.



Related Topics



Leave a reply



Submit