python datetie.time 对象根据 GPS 数据设置时区

python datetie.time object set timezone from GPS data

所以我在这里有点绝望,

我已经尝试在 5 小时内为从 GPS 接收到的 datetime.time 对象设置时区...

我目前有以下(有效)代码:

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))

但是,我想让 formatted.timestamp(当前返回为 00:00:00,例如 19:03:51)处于另一个时区 (Europe/Brussels)。

我怎样才能做到这一点?

我已经尝试了很多,但这里似乎没有任何效果....

如果您知道原始时区(例如美国东部时间),则可以使用 pytz

首先使用 localize() 设置时区,然后使用 astimezone() 转换为您想要的时区。此外,您需要根据可用数据格式化日期时间(这只是使用一个简单的字符串)。

这样的事情会有帮助吗?

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')

输出:

19:03:51 is the original time string
01:03:51 is the Europe/Brussels time