-1

Background

I have a dataframe, df: I would like to convert the date timestamps from UTC to PST in both columns.

  Connected                    Ended

  3/3/2020 1:00:00 PM          3/3/2020 1:01:00 PM
  3/4/2020 4:00:00 PM          3/4/2020 4:05:00 PM

Desired Output:

  ConnectedPST                 EndedPST

  3/3/2020 6:00:00 AM          3/3/2020 6:01:00 AM                    
  3/4/2020 9:00:00 AM          3/4/2020 9:05:00 AM

Structure:

   'Connected    Ended\n0  3/3/2020 1:00:00 PM  3/3/2020 1:01:00 PM\n1  3/4/2020     4:00:00 PM  3/4/2020 4:05:00 PM'

What I have tried:

 from datetime import datetime
 from pytz import timezone

 datetime_obj_pacific = timezone('US/Pacific').localize(datetime_obj_naive)
 print datetime_obj_pacific.strftime ("%Y-%m-%d %H:%M:%S %Z%z")

However, I am not sure how to incorporate this into my dataframe. Any assistance is appreciated.

Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41
Lynn
  • 4,292
  • 5
  • 21
  • 44
  • _However, I am not sure how to incorporate this into my dataframe._ Can you be more specific? Have you done any research, read the documentation? Also, please provide the data in a more convenient format. – AMC Apr 24 '20 at 02:43
  • I have done research and still am unsure about this. Why would you downvote as I am trying to learn and I provided what I have done within both of my recent questions. – Lynn Apr 24 '20 at 03:17
  • Does this answer your question? [Converting time zone pandas dataframe](https://stackoverflow.com/questions/22800079/converting-time-zone-pandas-dataframe) – AMC Apr 24 '20 at 03:25

1 Answers1

0

you can try something like this:

In [22]: import pandas as pd
    ...: d = pd.Series(['2020-04-23 19:57:55', '2020-04-23 19:59:46'])
    ...: d = pd.to_datetime(d)
    ...: d
    ...:
Out[22]:
0   2020-04-23 19:57:55
1   2020-04-23 19:59:46
dtype: datetime64[ns]

In [23]: d_pacific_tz_aware = d.dt.tz_localize("GMT").dt.tz_convert('America/Los_Angeles')

In [24]: d_pacific_tz_aware
Out[24]:
0   2020-04-23 12:57:55-07:00
1   2020-04-23 12:59:46-07:00
dtype: datetime64[ns, America/Los_Angeles]

In [25]: d_pacific_tz_naive = d.dt.tz_localize("GMT").dt.tz_convert('America/Los_Angeles').dt.tz_localize(None)

In [26]: d_pacific_tz_naive
Out[26]:
0   2020-04-23 12:57:55
1   2020-04-23 12:59:46
dtype: datetime64[ns]

You need to convert the column to datetime64[ns] format before changing the timezone

Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41