I have a data frame with date column as a date time format:
For eg: "2021-02-19T05:00:00 00:00"
I want to subtract some x hours from it. How can it be done?
CodePudding user response:
Let's say you have this timestamp:
time_str = '24/7/2021 11:13:08.230010'
It follows this format:
date_format_str = '%d/%m/%Y %H:%M:%S.%f'
You have to create a datetime object:
given_time = datetime.strptime(time_str, date_format_str)
then you just subtract n. ex n=4
n = 4
final_time = given_time - timedelta(hours=n)
And at then end you return to the initial format
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
CodePudding user response:
Here you are :
# 1. Import datetime
from datetime import datetime
# 2. Define function
def retrieve_hour(date_str: str, value: int):
return datetime.datetime.fromisoformat(date_str).hour - value
# Apply to pandas.Dataframe with the value
x = <VALUE>
data[COLUMN_NAME2] = data[COLUMN_NAME1].apply(retrieve_hour, x)
References https://docs.python.org/3.9/library/datetime.html#available-types