Python Forum
Assign a value if datetime is in between a particular time limit
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assign a value if datetime is in between a particular time limit
#1
Hi there,

I'm trying to assign a value to a dataframe if my DateTime column time value is belonging to a particular time frame.

I tried to use;
- pandas .between_time() method to identify whether the DateTime index column is belonging to a particular time frame
- then use numpy where() method to assign a particular value if the above condition is met


In my code below I had to first create a temporary dataframe to store pandas .between_time() result and assign the new value to this temp dataframe.
And then I update main dataframe with Temp dataframe value.

Is there a better way to do this without creating a temp dataframe?
For example, using pandas .loc() method to directly identify items in dataframe with the timeframe and assigned the value for such matching items

Appreciate your inputs.
import numpy as np
import pandas as pd


i = pd.date_range('2021-01-10', periods=6, freq='1D20min')
df = pd.DataFrame({'Value': ['No', 'No', 'No', 'No', 'No','No']}, index=i)

print(df)
Output:
Value 2021-01-10 00:00:00 No 2021-01-11 00:20:00 No 2021-01-12 00:40:00 No 2021-01-13 01:00:00 No 2021-01-14 01:20:00 No 2021-01-15 01:40:00 No
Temp = df.between_time('00:30', '01:30')
Temp['Value'] = "Yes"

df.update(Temp)
print(df)
Output:
Value 2021-01-10 00:00:00 No 2021-01-11 00:20:00 No 2021-01-12 00:40:00 Yes 2021-01-13 01:00:00 Yes 2021-01-14 01:20:00 Yes 2021-01-15 01:40:00 No
Reply
#2
see: https://pymotw.com/3/datetime/
Reply
#3
(Jan-01-2021, 11:05 AM)Larz60+ Wrote: see: https://pymotw.com/3/datetime/

No relevant content found for my question.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  datetime / time ifigazsi 5 7,057 Feb-01-2021, 01:21 AM
Last Post: snippsat
  Time Limit Exceeded error loves 5 3,077 Dec-03-2020, 07:15 AM
Last Post: Sofia_Grace
  TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' findbikash 2 9,515 Sep-18-2019, 08:32 AM
Last Post: buran
  fibonacci ***Time limit exceeded*** frequency 18 10,056 Nov-29-2018, 09:03 PM
Last Post: frequency
  'Time Limit Exceeded' Problem bkpee3 2 5,377 Nov-14-2018, 03:51 AM
Last Post: bkpee3
  If conditions with time limit unknowntothem 4 3,010 Nov-09-2018, 08:59 PM
Last Post: nilamo
  Convert from datetime to time.struct_time object chris0147 0 4,318 Mar-11-2018, 12:01 AM
Last Post: chris0147
  Subtract Minutes from Datetime.Time tkj80 2 42,942 May-11-2017, 09:56 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020