20

I have a lot of existing code that just uses the normal dateTime class in python, however in upgrading my program I am using the QtGui.QdateTimeEdit() class, but that class returns a QdateTime object that seems to be incompatible with the normal dateTime object.

So, is there a sane way to convert QdateTime to normal python dateTime? Other then breaking it into its parts and recreating a normal dateTime object from that? I am using PyQt4 with Python 3.2. Thanks.

John Doe
  • 3,436
  • 1
  • 18
  • 21
Scott C
  • 325
  • 1
  • 2
  • 7

3 Answers3

25

QDateTime has a toPyDateTime method which will return regular datetime objects.

In : from PyQt4 import QtCore

In : QtCore.PYQT_VERSION_STR
Out: '4.8.6'

In : QtCore.QT_VERSION_STR
Out: '4.7.4'

In : now = QtCore.QDateTime.currentDateTime()

In : now
Out: PyQt4.QtCore.QDateTime(2011, 12, 11, 20, 12, 47, 55)

In : now.toPyDateTime()
Out: datetime.datetime(2011, 12, 11, 20, 12, 47, 55000)
Avaris
  • 35,883
  • 7
  • 81
  • 72
  • thanks, I guess i missed that in the Docs, now i feel stupid but thanks anyways for showing me that! ;-) – Scott C Dec 12 '11 at 01:32
20

PyQt - use .toPyDateTime() on QtCore.QDateTime object

>>> from PyQt4.QtCore import QDateTime
>>> qdate = QDateTime(2012, 12, 20, 11, 59, 59)
>>> qdate
PyQt4.QtCore.QDateTime(2012, 12, 20, 11, 59, 59)
>>> date = qdate.toPyDateTime()
>>> date
datetime.datetime(2012, 12, 20, 11, 59, 59)

PySide - use .toPython() on QtCore.QDateTime object

>>> from PySide.QtCore import QDateTime
>>> qdate = QDateTime(2012, 12, 20, 11, 59, 59)
>>> qdate
PySide.QtCore.QDateTime(2012, 12, 20, 11, 59, 59, 0, 0)
>>> date = qdate.toPython()
>>> date
datetime.datetime(2012, 12, 20, 11, 59, 59)
Marcel Gwerder
  • 8,353
  • 5
  • 35
  • 60
John Doe
  • 3,436
  • 1
  • 18
  • 21
2
print(self.dte1.date().getDate())
print(self.dte1.date().toString("yyyy-MM-dd"))

you only need toString() method for python string

Jaap
  • 81,064
  • 34
  • 182
  • 193