I have to plot a column of data,but it is given in GMT format in python.I need to convert it into local time. I tried different codes given in this site for converting, but none of these worked
Asked
Active
Viewed 301 times
0
-
I think the question duplicates this one: [Convert UTC datetime string to local datetime](https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime) – LinPy May 07 '19 at 05:11
1 Answers
0
First step is to parse it into a proper datetime object:
import datetime
column_date_str_gmt = ...
gmt_datetime = datetime.datetime.strftime(column_date_str_gmt, '%Y-%m-%dT%H:%M:%SZ')
Then, move the gmt datetime over to UTC:
from datetime import timezone
utc_datetime= gmt_datetime.replace(tzinfo=timezone.utc).timestamp()
Finally, convert to local time:
import time
epoch = time.mktime(utc.timetuple())
epoch_offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch)
local_datetime = utc + epoch_offset

deepelement
- 2,457
- 1
- 25
- 25
-
,when i give the column name to the variable "column_date_str_gmt",it shows error. – Krishna Rajeev May 07 '19 at 06:50
-
Can you paste the error? the variable `column_date_str_gmt` is expecting a string value from your original dataset. – deepelement May 07 '19 at 15:04
-
File "
", line 4, in – Krishna Rajeev May 08 '19 at 04:20gmt_datetime = datetime.datetime.strftime(column_date_str_gmt, '%Y-%m-%dT%H:%M:%SZ') TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'numpy.ndarray' -
That means that you need to index the array to extract out your GTM column. Something like `myArray[2]` – deepelement May 08 '19 at 04:25
-
I am a beginner in python so I am confused about this.I took the data from excel using pandas which is stored in a variable 'b' and its of type numpy.ndarray.What should I do to this 'b' to make it local time – Krishna Rajeev May 08 '19 at 04:50