Compare QDateTime - python

self.start_date = ui.new_scheduled_transmition_day_start_date_2.date().toString()
self.time_start = ui.new_scheduled_transmition_day_start_time_2.time().toString()
self.end_date = ui.new_scheduled_transmition_day_end_date_2.date().toString()
self.end_time = ui.new_scheduled_transmition_day_end_time_2.time().toString()
I want to check if start_datetime<end_datetime.
Any advice would be useful.
I tried this:
date_1 = self.start_date+" "+self.time_start
date_2 = self.end_date+" "+self.end_time
date_1_time_obj = datetime.datetime.strptime(date_1, '%a %b %d %Y %H:%M:%S')
date_2_time_obj = datetime.datetime.strptime(date_2, '%a %b %d %Y %H:%M:%S')
print(date_1_time_obj<date_2_time_obj)
Error:
ValueError: time data '╙άέ ╔άΊ 1 2000 00:00:00' does not match format '%a %b %d %Y %H:%M:%S'
The error happens because .toString() returns day of week and month in local format (greek characters)

self.start_date = ui.new_scheduled_transmition_day_start_date_2.date().toPyDate()
self.time_start = ui.new_scheduled_transmition_day_start_time_2.time().toPyTime()
self.end_date = ui.new_scheduled_transmition_day_end_date_2.date().toPyDate()
self.end_time = ui.new_scheduled_transmition_day_end_time_2.time().toPyTime()
date_1_time_obj = datetime.datetime.combine(self.start_date, self.time_start)
date_2_time_obj = datetime.datetime.combine(self.end_date, self.end_time)
print(date_1_time_obj<date_2_time_obj)

If you want to do just what your title says: compare objects of type QDateTime, that's already possible just like that.
date1 = QDateTime.currentDateTime()
date2 = QDateTime.currentDateTime().addMonths(1)
date1 < date2
=> True
And if you want to combine the date and the time first it should go about this way:
start_date = ui.new_scheduled_transmition_day_start_date_2
start_time = ui.new_scheduled_transmition_day_start_time_2
end_date = ui.new_scheduled_transmition_day_end_date_2
end_time = ui.new_scheduled_transmition_day_end_time_2
date_1 = QDateTime(start_date).addMSecs(start_time.msecsSinceStartOfDay())
date_2 = QDateTime(end_date).addMSecs(end_time.msecsSinceStartOfDay())
date1 < date2
See https://doc.qt.io/qtforpython/PySide2/QtCore/QDateTime.html#PySide2.QtCore.PySide2.QtCore.QDateTime.__lt__ for more information.

Related

If conditions with datetime comparisons

def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
return datetimeobj - datetime.datetime.today()
My above functions asks for strdate and it expects data similar to this
Sun, Dec 12 / 3:00 AM 2022 and the output will be a remaining count of days and hours til that date.
If the remaining days is a negative amount of days I'd like to increase the datetime object by one year and output the count
How do I do this?
To check the days remaining on your timedelta object, you can access the attribute days.
def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
delta = datetimeobj - datetime.datetime.today()
if delta.days < 0:
... # do your thing
return delta
Note here that delta is of type datetime.timedelta, and it ONLY holds days, seconds and microseconds. Hence, you can't increment the year value on it.
If you insist on incrementing a year on that timedelta, you can just add 365 days to it ...
def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
delta = datetimeobj - datetime.datetime.today()
if delta.days < 0:
return delta + datetime.timedelta(days=365)
return delta

How to correctly compare the current date with the date of the site (just the day) from which the publication is parsed with today's date?

I need to parse exactly those publications where the publication date coincides with today's date. I only need to match the day. For example, 20 = 20. Here's what I did, but this is not good code:
today = date.today()
d2 = today.strftime("%B %d, %Y")
today_day = d2[8] + d2[9]
for el in items:
title = el.select('.card-stats > div')
p = title[1].text
space = p.replace(" ","")
day = space[1] + space[2]
if day == today_day:
data_id = el.get('data-id')
I think that the mistake could be in the second part of your code where you throw a variable, day, you didn't define before.
Try:
today = date.today()
d2 = today.strftime("%B %d, %Y")
today_day = d2[8] + d2[9]
for el in items:
title = el.select('.card-stats > div')
p = title[1].text
space = p.replace(" ","")
day = space[1] + space[2]
if today == today_day:
data_id = el.get('data-id')

Python: Hours between two datetimes by day

I tried to develop a Python function that determines the difference between two datetime objects. I need an algorithm that calculates the number of hours per day. Is there a built-in function for this?
from datetime import datetime, timedelta, date
def getHoursByDay(dateA, dateB):
...
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
hours = getHoursByDay(dateA, dateB)
print hours
# {
# '2018-09-01': 15,
# '2018-09-02': 24,
# '2018-09-03': 11.5,
# }
There is no built-in function, though it is very simple to build one.
from datetime import datetime, timedelta, time
def deltaByDay(dateA, dateB):
dateAstart = datetime.combine(dateA, time())
dateBstart = datetime.combine(dateB, time())
result = {}
oneday = timedelta(1)
if dateAstart == dateBstart:
result[dateA.date()] = dateB - dateA
else:
nextDate = dateAstart + oneday
result[dateA.date()] = nextDate - dateA
while nextDate < dateBstart:
result[nextDate.date()] = oneday
nextDate += oneday
result[dateB.date()] = dateB - dateBstart
return result
def deltaToHours(delta, ndigits=None):
return delta.days * 24 + round(delta.seconds / 3600.0, ndigits)
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
deltas = deltaByDay(dateA, dateB);
output = {k.strftime('%Y-%m-%d'): deltaToHours(v, 1) for k, v in deltas.items()}
print(output)
# => {'2018-09-01': 15.0, '2018-09-02': 24.0, '2018-09-03': 11.5}
The built in timedelta functions would be able to get you the total days, and the remaining hours difference. If you want the output specifically in that dictionary format posted you would have to create it manually like this:
from datetime import datetime, time, timedelta
def getHoursByDay(dateA, dateB):
if dateA.strftime("%Y-%m-%d") == dateB.strftime("%Y-%m-%d"):
return {dateA.strftime("%Y-%m-%d"): abs(b-a).seconds / 3600}
result = {}
delta = dateB - dateA
tomorrow = dateA + timedelta(days=1)
day1 = datetime.combine(tomorrow, time.min) - dateA
result[dateA.strftime("%Y-%m-%d")] = day1.seconds / 3600
for day in range(1, delta.days):
result[(dateA + timedelta(days=day)).strftime("%Y-%m-%d")] = 24
priorday = dateB - timedelta(days1)
lastday = dateB - datetime.combine(priorday, time.min)
result[dateB.strftime("%Y-%m-%d")] = lastday.seconds / 3600
return result
Essentially this function calculates the first day and the last day values, then populates all the days in between with 24.
There is a kind of simple way to do this.
hours = (dateA - dateB).hours
I've used this to caclulate a difference in days.
https://docs.python.org/2/library/datetime.html#datetime.timedelta

Converting 12 hour format time string (with am/pm) into UTC in 24 hour format

I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)

calculate dates in python

def main(filename, from_str, to_str):
date_from =time.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = time.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
if __name__ == "__main__":
if len(sys.argv) < 1:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
sys.exit(1)
main("servanet-" + sys.argv[1] + sys.argv[2]+ ".txt", sys.argv[1] + " 00:00", sys.argv[2] + " 23:59")
This is part of my code, I want to calculate the days from the input, (I don't need to calculate minutes and seconds,just days in this case, but I will use the minute and the second information later in the code, so I need to keep them like this) ,but it seems, (date_from - date_to).days cannot work with minutes and seconds after it, how can I solve this problem?
Many thanks!
========comments: I think I cannot simply use day2-day1. since if they are from different month, the result will be wrong, like from 2011-08-01 to 2011-09-02
Use datetime.datetime.strptime instead of time.strptime:
time.striptime returns a time.struct_time object which does not support subtraction. In contrast, datetime.datetime.strptime returns a datetime.datetime object, which does support date arithmetic.
import datetime as dt
def main(filename, from_str, to_str):
date_from = dt.datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = dt.datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
yields
% test.py '2011-09-08' '2011-10-08'
2011-09-08 00:00:00 2011-10-08 23:59:00
-31
By the way, sys.argv is always at least of length 1. The first item is the name of the calling program. So I think you need
if __name__ == "__main__":
if len(sys.argv) <= 2:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
instead of if len(sys.argv) < 1.
import datetime
import time
def parse_date(date_str):
if ' ' in date_str:
return time.strptime(date_str, "%Y-%m-%d %H:%M")
else:
return time.strptime(date_str, "%Y-%m-%d")
def main(filename, from_str, to_str):
date_from = parse_date(from_str)
date_to = parse_date(to_str)
print date_from, date_to
days = (datetime.date(*date_to[:3]) - datetime.date(*date_from[:3])).days
print days
I am not sure what you mean "cannot with minutes and seconds" after it. But I modified your function a little bit and it should be fine:
def main(filename, from_str, to_str):
date_from = datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_to - date_from).days
print days
main("", "2011-09-08 00:00", "2011-10-09 00:00")
main("", "2011-09-08 00:00", "2011-10-08 23:59")
main("", "2011-09-08 00:00", "2011-10-08 00:00")
>>> 2011-09-08 00:00:00 2011-10-09 00:00:00
31
2011-09-08 00:00:00 2011-10-08 23:59:00
30
2011-09-08 00:00:00 2011-10-08 00:00:00
30

Categories

Resources