gabediq
gabediq

Reputation: 1

How to convert a string to a time, make it time-zone aware, and convert the timezone in Python?

I have a column called 'Status Date' with thousands of dates formatted like this:

Status Date
01/04/2021-12:21:36

in the pattern:

m/d/Y-H:M:S

I need all the elements of this column to be converted to a time-zone aware DateTime object in UTC, and the times to be subsequently converted to UTC-0600 (America/Chicago). I attempted to fix it myself using this:

merged['Status Date'] = pd.to_datetime(merged['Status Date'], errors='coerce')
merged['Status Date'] = merged['Status Date'].dt.tz_localize('utc').dt.tz_convert('America/Chicago')

However this ignores the date formatting I have and doesn't read in a time, instead converting everything to 00:00:00, and then to 18:00:00-06:00. When I run this, I get this output:

2021-01-03 18:00:00-06:00

which disregards the time and pushes everything back 6 hours from 00:00:00.

Any help would be appreciated, I feel like I'm close.

Upvotes: 0

Views: 69

Answers (1)

mullinscr
mullinscr

Reputation: 1738

Try this on your to_datetime() creation

merged['Status Date'] = pd.to_datetime(merged['Status Date'],
    errors='coerce', format='m/d/Y-H:M:S')

Upvotes: 1

Related Questions