User Tools

Site Tools


bloglike:2021-10

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
bloglike:2021-10 [2021/10/17 05:48] – add signature styblabloglike:2021-10 [2021/10/17 06:41] (current) – PyQt5, QDateTime, UTC and localtime/timezone stybla
Line 10: Line 10:
  
  --- //[[stybla@turnovfree.net|Zdenek Styblik]] 2021/10/16 18:37//  --- //[[stybla@turnovfree.net|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:
 +
 +<code python>
 +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'
 +</code>
 +
 +Actually, I needed something like this:
 +
 +<code python>
 +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')))
 +</code>
 +
 +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 [[https://datatracker.ietf.org/doc/html/rfc3339|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 [[https://stackoverflow.com/questions/4030511/convert-a-qdatetime-in-utc-to-local-system-time|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.
 +
 + --- //[[stybla@turnovfree.net|Zdenek Styblik]] 2021/10/17 11:40//
bloglike/2021-10.txt · Last modified: 2021/10/17 06:41 by stybla