-1

I am trying to extract the hour from the column date in a 24-h format. It doesn't seem to work as I am only getting the AM, from the following dataset: Chicago crime

df["timestamp"] = pd.to_datetime(df["date"])
# Convert timestamp to AM/PM format
df["timestamp"] = df["timestamp"].apply(lambda x: x.strftime("%Y-%m-%d %I:%M:%S %p"))
df['hour'] = df['timestamp'].dt.hour

The hour part is from 1-12, however, I don’t seem to have the AM/PM, but only the UTC in the time stamp.
Data in the time stamp column - date, is shown below;

date
-----------------------
2019-08-29 06:40:00 UTC
2010-03-07 01:21:00 UTC
2002-10-22 11:09:33 UTC
2012-02-20 09:00:00 UTC
2022-10-04 07:24:00 UTC
2005-09-28 04:00:00 UTC
2001-11-21 02:01:03 UTC
2021-01-24 01:00:00 UTC
2005-12-10 08:00:00 UTC
2011-10-18 04:00:00 UTC
2008-02-06 01:00:00 UTC
2001-07-30 03:36:18 UTC
2015-10-11 05:00:00 UTC
2010-02-04 10:15:00 UTC
2003-08-01 04:38:49 UTC
moken
  • 3,227
  • 8
  • 13
  • 23
dim GOROH
  • 1
  • 1
  • 1
    Please include a sample of the data in the question. For more info, see [mre] and [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Mar 05 '23 at 04:21
  • Hey I added a link for the whole data set for reference, the column I’m interested in is column date – dim GOROH Mar 05 '23 at 05:36
  • Sorry if I wasn't clear, it needs to be as text, [not a picture](https://meta.stackoverflow.com/q/285551/4518341). – wjandrea Mar 05 '23 at 18:38

1 Answers1

0

Using the following version you can extract the hour from the sample without the need to convert the datatype of entire column.

from datetime import datetime
sample = "2019-08-29 06:40:00 UTC"
parsed_sample = datetime.strptime(sample, "%Y-%m-%d %H:%M:%S %Z")
hour = parsed_sample.hour

Here %Z represents the time zone.

Dhruv Awasthi
  • 149
  • 1
  • 4