So I'm kinda hopeless here,
I've tried in the pass 5 hours to set the timezone for a datetime.time
object, received from a GPS...
I currently have the following (working) code:
import serial
import string
import pynmea2
ser = serial.Serial()
ser.port = "/dev/ttyS0"
ser.baudrate = 9600
ser.timeout = 1
ser.open()
while True:
data = ser.readline()
if (data.startswith("$GPGGA")):
formatted = pynmea2.parse(data)
# print(data)
print('Latitude: {}'.format(formatted.lat))
print('Longitude: {}'.format(formatted.lon))
print('Timestamp: {}'.format(formatted.timestamp))
print('Signal Quality: {}'.format(formatted.gps_qual))
print('Number sats: {}'.format(formatted.num_sats))
However, I want to have the formatted.timestamp
, which currently is returned as 00:00:00
, for example 19:03:51
, to be in another timezone (Europe/Brussels
).
How can I achieve this?
I tried alot already, but nothing seems to work here....
If you know the original timezone (e.g. US Eastern), you can use pytz.
First you set the timezone with localize()
and then use astimezone()
to convert to your desired timezone. Also, you will need to format your datetime from the available data (this is just using a simple string).
Would something like this be helpful?
import datetime
import pytz
tz_eastern = pytz.timezone('US/Eastern')
tz_brussels = pytz.timezone('Europe/Brussels')
time_date_string = '2019-08-20 19:03:51'
brussels_time = tz_eastern.localize(
datetime.datetime.strptime(time_date_string,
'%Y-%m-%d %H:%M:%S'))\
.astimezone(tz_brussels)\
.strftime("%H:%M:%S")
print(f'{time_date_string.split(" ")[1]} is the original time string'
f'\n{brussels_time} is the {tz_brussels} time')
Outputs:
19:03:51 is the original time string
01:03:51 is the Europe/Brussels time