Convert QDate to seconds

Deadly 提交于 2019-12-02 05:33:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!