Forklift17
Forklift17

Reputation: 2477

Creating a new column of local times from correct UTC times

from datetime import datetime
import pandas as pd
import pytz

times = pd.DataFrame(
    {'Time':['2020-03-14 12:00:00']*5,
     'TimeZone':['US/Pacific','US/Arizona','US/Mountain',
                 'US/Central','US/Eastern']})
times.Time = times.Time.map(
    lambda x: datetime.fromisoformat(x).astimezone(pytz.utc))
times.TimeZone = times.TimeZone.map(pytz.timezone)

I want to do two things with this script.

  1. Before any further operations, I want times.Time to all be 12:00 noon in UTC instead of mapping forward/backward based on my local time zone. Ideally I want this script to run the same anywhere in the world without having to manually account for the machine's local time zone.
  2. I want to create a third column of datetime objects that are the same time as times.Time but in times.TimeZone time zones.

How can I do this?

Upvotes: 1

Views: 155

Answers (1)

Code Different
Code Different

Reputation: 93161

For #1, you should use pd.to_datetime followed by tz_localize. For #2, it's a tz_convert:

times['Time'] = pd.to_datetime(times['Time']).dt.tz_localize('utc')
times['TimeZone'] = times['TimeZone'].map(pytz.timezone)

# This operation is not vectorized (read: slow)
times['LocalTime'] = times.apply(lambda row: row['Time'].tz_convert(row['TimeZone']), axis=1)

Result:

                       Time     TimeZone                  LocalTime
0 2020-03-14 12:00:00+00:00   US/Pacific  2020-03-14 05:00:00-07:00
1 2020-03-14 12:00:00+00:00   US/Arizona  2020-03-14 05:00:00-07:00
2 2020-03-14 12:00:00+00:00  US/Mountain  2020-03-14 06:00:00-06:00
3 2020-03-14 12:00:00+00:00   US/Central  2020-03-14 07:00:00-05:00
4 2020-03-14 12:00:00+00:00   US/Eastern  2020-03-14 08:00:00-04:00

Upvotes: 1

Related Questions