2

I take date from QDateTimeEdit and convert it to seconds like this:

import time
from datetime import datetime

date = self.__ui.dateTimeEdit.date().toString("dd/MM/yy")
dateString = str(date)

seconds = time.mktime(datetime.strptime(dateString, "%d/%m/%y").timetuple()) 

This works well, but since it looks to long to me, my question is: Is it possible to convert self.__ui.dateTimeEdit.date() directly, without those string conversions?

EDIT1 Unfortunately toMSecsSinceEpoch() as falsetru suggested, doesn't work for me.

AttributeError: 'QDateTime' object has no attribute 'toMSecsSinceEpoch'

I'm using PyQt 4.7.1 for Python 2.6

EDIT2 based on jonrsharpe's answer I've escaped string conversions:

    date = self.__ui.dateTimeEdit.date().toPyDate()
    seconds = time.mktime(date.timetuple()) 

result is the same.

EDIT3 even shorter solution based on falsetru's comment:

self.__ui.dateTimeEdit.dateTime().toTime_t()
Aleksandar
  • 3,541
  • 4
  • 34
  • 57

2 Answers2

2

Use QDateTime.toMSecsSinceEpoch:

>>> import PyQt4.QtCore
>>> d = PyQt4.QtCore.QDateTime(2014, 2, 20, 17, 10, 30)
>>> d.toMSecsSinceEpoch() / 1000
1392883830L

UPDATE

Alternative using QDateTime.toTime_t:

>>> d = PyQt4.QtCore.QDateTime(2014, 2, 20, 17, 10, 30)
>>> d.toTime_t()
1392883830L
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Tnx for answer, I get this error: `AttributeError: 'QDateTime' object has no attribute 'toMSecsSinceEpoch'` . I'm using Python 2.6, PyQt4, is that a problem? – Aleksandar Feb 20 '14 at 09:00
  • @Aleksandar, It works for me. I'm using Python 2.7.6 + PyQt4 4.10.2. – falsetru Feb 20 '14 at 09:02
  • @Aleksandar, According to [Qt QDateTime Class documentation](http://qt-project.org/doc/qt-5/qdatetime.html#toMSecsSinceEpoch), the method is introduced in Qt 4.7. Check you Qt/PyQt version. – falsetru Feb 20 '14 at 09:33
  • @Aleksandar, Did you try jonrsharpe's answer? If that does not work, try `toPyDateTime`. – falsetru Feb 20 '14 at 09:38
  • @Aleksandar, Did you try `self.__ui.dateTimeEdit.toTime_t()` ? – falsetru Feb 20 '14 at 09:44
  • `'QDateTimeEdit' object has no attribute 'toTime_t'` It's maybe because of python 2.6 – Aleksandar Feb 20 '14 at 09:59
  • @Aleksandar, Ah, missed `dateTime()`: `self.__ui.dateTimeEdit.dateTime().toTime_t()` – falsetru Feb 20 '14 at 10:01
1

The QDate you get from

self.__ui.dateTimeEdit.date()

has another method toPyDate that will save you the round trip through a string.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437