简体   繁体   中英

How to get the exact time after converting from UTC to any other time zone in Python?

I've a data with time columns, which I have to convert from utc to ist

example

utc_datetime         tag_value   inserted_at
2018-12-03 16:48:32  3.38        2018-12-03 22:18:48 

I've used the following code to convert time in UTC to IST

data = data.rename(columns={"utc_datetime": "ist_datetime"})
data['ist_datetime'] = pd.to_datetime(data['ist_datetime'], errors='coerce') 
data['ist_datetime'] = pd.to_datetime(data['ist_datetime'], errors='coerce')
data['inserted_at'] = pd.to_datetime(data['inserted_at'], errors='coerce')
data['ist_datetime'] = data['ist_datetime'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
data['inserted_at'] = data['inserted_at'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')

For which I'm getting the output like

在此处输入图像描述

What should I do to get the exact converted time and not + 5:30 with the original time?

Eg - '16:18:32' to '21:48:32' and not '16:18:32 + 5:30'

Thanks

From your comment, I think you may be mistaken about the source data.

For example:

import datetime
import pandas as pd

dt = pd.to_datetime([datetime.datetime(2018, 1, 1, 0, 0, 0)])
print(dt)
print(dt.tz_localize('UTC'))
print(dt.tz_localize('UTC').tz_convert('Asia/Kolkata'))

Works exactly as you expect:

DatetimeIndex(['2018-01-01'], dtype='datetime64[ns]', freq=None)
DatetimeIndex(['2018-01-01 00:00:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)
DatetimeIndex(['2018-01-01 05:30:00+05:30'], dtype='datetime64[ns, Asia/Kolkata]', freq=None)

You don't provide us with the source data, only the result you think is wrong - you'd have to provide a more complete example, with output of the source data to make clear what the problem is, if you believe there still actually is one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM