1. Support Center
  2. Python for Data Science Recipes

Extracting Parts of a Date or Time from a TimeStamp

using python to extract date components (month, year, minute...) from a datetime strimg

 

For example, let’s imagine that you want a column that contains just a date so that you can summarize the data by Date, or maybe by Date and Hour or some other part of the timestamp. Now, you can write a loop to go down row by row and copy the first 10 characters from a timestamp in string format (yyyy-mm-dd) but trust me, that can take a long time, use the following command to do it quickly. Creating my own version of the timestamp is probably my most used command…


df = liberator.get_dataframe(liberator.query(name = 'minute_bars', symbols = 'SPY', as_of = '2024-07-26', back_to = '2024-07-25'))

df['Date'] = df.apply(lambda row: str(row.timestamp)[0:10], axis = 1)

df['Time'] = df.apply(lambda row: str(row.timestamp)[11:16], axis = 1)

df['Hour'] = df.apply(lambda row: str(row.timestamp)[11:13], axis = 1)

df['DateTime'] = df.apply(lambda row: str(row.timestamp)[0:16], axis = 1)

df['DateHour'] = df.apply(lambda row: str(row.timestamp)[0:13], axis = 1)

df[['timestamp','Date','Time','Hour','DateTime','DateHour']]

timestamps_in_dataframe

Alternative FLOOR method…


df['seconds'] = df['timestamp'],dt,floor('s')

# https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.floor.html

df7['Date’] = pd.to_datetime(df["timestamp"]).dt.date  # Convert str to DateTime and pull out Date

https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.date.html