Skip to content
Advertisement

Converting UTC time to local in python datetime.time [closed]

My sample dataframe is:

df = pd.DataFrame({'time':['00:00:00','03:00:00','06:00:00','09:00:00','12:00:00'],
              'value':[850,np.nan,500,650,780]})

Here, the time are in UTC, I want to convert the time to local time such that:

Local time = UTC + 5:15

Any help would be highly appreciated.

Advertisement

Answer

Perhaps datetime.timedelta?

>>> import pandas as pd
>>> import numpy as np
>>> from datetime import timedelta
>>> df = pd.DataFrame({'time':['00:00:00','03:00:00','06:00:00','09:00:00','12:00:00'],
...               'value':[850,np.nan,500,650,780]})
>>> df
       time  value
0  00:00:00  850.0
1  03:00:00    NaN
2  06:00:00  500.0
3  09:00:00  650.0
4  12:00:00  780.0
>>> df['time'] = df['time'].astype('datetime64')
>>> df
                 time  value
0 2021-06-14 00:00:00  850.0
1 2021-06-14 03:00:00    NaN
2 2021-06-14 06:00:00  500.0
3 2021-06-14 09:00:00  650.0
4 2021-06-14 12:00:00  780.0
>>> d = timedelta(hours=5, minutes=15)
>>> print(d)
5:15:00
>>> df['time'] = df['time'].apply(lambda v: v+d)
>>> df
                 time  value
0 2021-06-14 05:15:00  850.0
1 2021-06-14 08:15:00    NaN
2 2021-06-14 11:15:00  500.0
3 2021-06-14 14:15:00  650.0
4 2021-06-14 17:15:00  780.0
>>> df['time'] = df['time'].apply(lambda v: v.strftime('%H:%M:%S'))
>>> df
       time  value
0  05:15:00  850.0
1  08:15:00    NaN
2  11:15:00  500.0
3  14:15:00  650.0
4  17:15:00  780.0
>>>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement