I have a dataframe that looks like that:
conversation__created_at
0 2020年10月15日T03:39:42.766773+00:00
1 2020年10月14日T11:24:33.831177+00:00
2 2020年10月14日T08:29:44.192258+00:00
3 2020年10月14日T01:42:06.674313+00:00
4 2020年10月13日T12:57:04.218184+00:00
How to convert it into GMT +7?
avarice
15.7k3 gold badges19 silver badges38 bronze badges
4 Answers 4
I assume you have a pandas series because the data you posted looks like one.
Then you can use tz_convert, i.e.
import pandas as pd
pd.to_datetime('2020-10-15T03:39:42.766773+00:00').tz_convert('Etc/GMT+7')
As pointed out in the comments, since the datetime carries a T in it, it is of string format, thus we need to convert to datetime first and then convert to the correct timezone.
pd.to_datetime(series).dt.tz_convert('Etc/GMT+7')
Sign up to request clarification or add additional context in comments.
5 Comments
FObersteiner
the OP's input is of dtype string since there still is the 'T' separator between date and time, so pd.to_datetime presumably is required ;-)
Stefan
@MrFuppes, thanks for pointing that out. I never noticed that
T is actually indicating string fromat. I updated my answer.FObersteiner
oh and there's one more caveat;
'Etc/GMT+7' is UTC-7 (not +7). not sure what the OP expects here. would be easier if a certain time zone was named.ab.trubex
so what's the syntax for +7 (Jakarta)?
Stefan
@ab.trubex There is the timezone
Asia/Jakarta, so you can use this one.You can use datetime library only.
from datetime import datetime, timedelta, timezone
d = datetime.fromisoformat("2020年10月15日T03:39:42.766773+00:00")
tz = timezone(timedelta(hours=7))
new_time = d.astimezone(tz)
answered Oct 26, 2020 at 7:20
HK boy
1,40411 gold badges21 silver badges27 bronze badges
you can use pytz to set timezone for your datetime instance
for example:
from pytz import timezone
from datetime import datetime
date = datetime.now()
print(date)
tz = timezone("Etc/GMT+7")
date = date.replace(tzinfo=tz)
print(date)
out put:
2020年10月26日 10:33:25.934699
2020年10月26日 10:33:25.934699-07:00
answered Oct 26, 2020 at 7:05
Arsham Mohammadi
4012 silver badges7 bronze badges
Comments
You can apply pytz.timezone on the df
from pytz import timezone
from datetime import datetime
def myDate(x):
tz = timezone("Etc/GMT+7")
dt = x.replace(tzinfo=tz)
return dt
df['conversation__created_at'] = df.apply(lambda row: myDate(row['conversation__created_at'].to_pydatetime()))
answered Oct 26, 2020 at 7:13
avarice
15.7k3 gold badges19 silver badges38 bronze badges
2 Comments
ab.trubex
once more things, i add df = pd.read_csv('filename.csv')
FObersteiner
besides that there is a pandas built-in for this task, I think you shouldn't suggest to use
replace here. Although this works for static offsets, it causes wrong offsets (LMT) for actual time zones, see pytz localize vs. replace.lang-py