问题
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()
回答1:
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
回答2:
The QDate
you get from
self.__ui.dateTimeEdit.date()
has another method toPyDate that will save you the round trip through a string.
来源:https://stackoverflow.com/questions/21901736/convert-qdate-to-seconds