Table of Contents

Issue 2021 - October

Buying from China? Free shipping?

Well, I hope you're not in a hurry, because if it wasn't fast before, it didn't get any faster that's for sure.

I'm not complaining, however it's something to be aware of. Why not to buy local you ask? As long as price is 3-10x more, why would I or anyone for that matter? Where do you think “local” shops buy it from? Now, don't get me wrong because I understand they have to make living too. It's still a no in this case.

Zdenek Styblik 2021/10/16 18:37

PyQt5, QDateTime, UTC and localtime/timezone

I cannot believe it took me hour or longer to figure this one out:

from PyQt5.QtCore import QDateTime
from PyQt5.QtCore import QTimeZone
 
utc_datetime = QDateTime.fromString('2021-10-16T23:15:52Z', 'yyyy-MM-ddTHH:mm:ssZ')
utc_datetime.setTimeZone(QTimeZone.utc())
local_datetime = utc_datetime.toLocalTime()
print(local_datetime.toString('yyyy-MM-ddTHH:mm:ssZ'))
# '2021-10-17T01:15:52Z'

Actually, I needed something like this:

from PyQt5.QtCore import QDateTime
from PyQt5.QtCore import QTimeZone
 
local_datetime = QDateTime.currentDateTime()
print('local DT: {}'.format(local_datetime.toString('yyyy-MM-ddTHH:mm:ssZ')))
utc_datetime = local_datetime.toUTC()
stored_dt = utc_datetime.toString("yyyy-MM-ddTHH:mm:ssZ")
print('stored utc DT: {}'.format(stored_dt))
utc_datetime = QDateTime.fromString(stored_dt, 'yyyy-MM-ddTHH:mm:ssZ')
utc_datetime.setTimeZone(QTimeZone.utc())
print('utc DT: {}'.format(utc_datetime.toString('yyyy-MM-ddTHH:mm:ssZ')))
local_datetime = utc_datetime.toLocalTime()
print('local DT: {}'.format(local_datetime.toString('yyyy-MM-ddTHH:mm:ssZ')))

In other words convert local date and time into UTC, store it as a a string and then restore it. Whether it makes sense or not, that's another question. Now, the problem was to figure out how to set that timezone or something. No, QDateTime doesn't know anything about timezone, not if you use RFC3339(that Z is just for show here, unfortunately). I had to find QTimeZone module first. That was easy, but it was not working for whatever reason. Maybe I was just tired and overlooking something. Then I found similar question at StackOverflow which led to the hunt for a mysterious TimeSpec which I couldn't find anywhere in PyQt5. I found it in PySide2, though. Pointlessly, because apparently it's not needed for anything, at least in this case. Everything works as I need to now.

Zdenek Styblik 2021/10/17 11:40