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
Related
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.
So I'm trying to print the total hours in intervals between a start date and an end date in python as follows:
#app.route('/test/')
def test():
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def daterange(start_date_time, end_date_time):
for n in range(int ((end_date_time - start_date_time).days)):
yield start_date_time + timedelta(n)
for single_date in daterange(start_date_time, end_date_time):
def get_delta(start_date_time, end_date_time):
delta = end_date_time - start_date_time
return delta
# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
currtime = start_date_time + timedelta(hours=i)
print (currtime)
return ("done")
By This i'm only managing to get the first 24 Hours from the selected date, but I wish to keep on counting and get all hours till the selected end date.
You might be overthinking it.
from datetime import datetime, timedelta
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def get_delta(l, r):
return abs(int((l-r).total_seconds())) / 3600
for h in range(int(get_delta(start_date_time, end_date_time))):
print((start_date_time + timedelta(0, h*3600)).strftime(date_format))
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
I have a function that can be used to print a datetime.datetime object in a specified style. I want to be able to print in similar styles the information contained in a datetime.timedelta object. How could the datetime.timedelta object be manipulated such that it can be styled easily, like by using the function that's already defined?
My code is below (and the answer should be around 82 days, 14 hours).
#!/usr/bin/env python
import datetime
def main():
print("current time UTC:\n")
print(
style_datetime_object(
datetime_object = datetime.datetime.utcnow(),
style = "HH hours MM minutes SS seconds day DD month YYYY"
)
)
year_ICHEP_2016 = 2016
month_ICHEP_2016 = 8
day_ICHEP_2016 = 3
datetime_object_ICHEP_2016_time = datetime.datetime(
year_ICHEP_2016,
month_ICHEP_2016,
day_ICHEP_2016
)
datetime_object_current_time_UTC = datetime.datetime.utcnow()
datetime_object_current_time_UTC_to_ICHEP_2016_time =\
datetime_object_ICHEP_2016_time - datetime_object_current_time_UTC
# insert magic to style datetime.timedelta
# `datetime_object_current_time_UTC_to_ICHEP_2016_time' using function
# `style_datetime_object`
#
# print(
# style_datetime_object(
# datetime_object = datetime_object_current_time_UTC_to_ICHEP_2016_time,
# style = "HH hours MM minutes SS seconds day DD month YYYY"
# )
# )
def style_datetime_object(
datetime_object = None,
style = "YYYY-MM-DDTHHMMZ"
):
# filename safe
if style == "YYYY-MM-DDTHHMMZ":
return datetime_object.strftime("%Y-%m-%dT%H%MZ")
# filename safe with seconds
elif style == "YYYY-MM-DDTHHMMSSZ":
return datetime_object.strftime("%Y-%m-%dT%H%M%SZ")
# filename safe with seconds and microseconds
elif style == "YYYY-MM-DDTHHMMSSMMMMMMZ":
return datetime_object.strftime("%Y-%m-%dT%H%M%S%fZ")
# elegant
elif style == "YYYY-MM-DD HH:MM:SS UTC":
return datetime_object.strftime("%Y-%m-%d %H:%M:%SZ")
# UNIX time in seconds with second fraction
elif style == "UNIX time S.SSSSSS":
return (datetime_object -\
datetime.datetime.utcfromtimestamp(0)).total_seconds()
# UNIX time in seconds rounded
elif style == "UNIX time S":
return int((datetime_object -\
datetime.datetime.utcfromtimestamp(0)).total_seconds())
# human-readable date
elif style == "day DD month YYYY":
return datetime_object.strftime("%A %d %B %Y")
# human-readable time and date
elif style == "HH:MM day DD month YYYY":
return datetime_object.strftime("%H:%M %A %d %B %Y")
# human-readable time with seconds and date
elif style == "HH:MM:SS day DD month YYYY":
return datetime_object.strftime("%H:%M:%S %A %d %B %Y")
# human-readable date with time with seconds
elif style == "day DD month YYYY HH:MM:SS":
return datetime_object.strftime("%A %d %B %Y %H:%M:%S")
# human-readable-audible time with seconds and date
elif style == "HH hours MM minutes SS seconds day DD month YYYY":
return datetime_object.strftime("%H hours %M minutes %S seconds %A %d %B %Y")
# human-readable days, hours and minutes
elif style == "DD:HH:MM":
return datetime_object.strftime("%d:%H:%M")
# human-readable days, hours, minutes and seconds
elif style == "DD:HH:MM:SS":
return datetime_object.strftime("%d:%H:%M:%S")
# human-readable time with seconds
elif style == "HH:MM:SS":
return datetime_object.strftime("%H:%M:%S")
# human-readable-audible time with seconds
elif style == "HH hours MM minutes SS seconds":
return datetime_object.strftime("%H hours %M minutes %S seconds")
# filename safe
else:
return datetime_object.strftime("%Y-%m-%dT%H%MZ")
if __name__ == '__main__':
main()
I am getting this error in python 3.4
I am not sure what I am doing wrong.
This is my code
print(time.ctime(int(self._start)))
current = datetime.strptime(time.ctime(int(self._start)),"%m/%d/%Y %H:%M:%S")
print("current",current)
Thank you Alex:
My final code ended up being this.
parsed = datetime.strptime(time.ctime(int(self._start)),"%a %b %d %H:%M:%S %Y")
current = parsed.strftime('%m/%d/%y %H:%M:%S')
Indeed, Wed Jan 14 definitely does not "match format" %m/%d/%Y!
You can parse that string as '%a %b %d %H:%M:%S %Y'. For example:
>>> thestr = time.ctime()
>>> thestr
'Wed Jan 14 18:53:48 2015'
>>> parsed = datetime.datetime.strptime(thestr, '%a %b %d %H:%M:%S %Y')
>>> parsed
datetime.datetime(2015, 1, 14, 18, 53, 48)
Try this method of time formatting instead:
import datetime
now = datetime.datetime.now()
mo, d, y = now.month, now.day, now.year
h, mi, s = now.hour, now.minute, now.second
print '%d/%d/%d %d:%d:%d' % (mo, d, y, h, mi, s)
You can change to 12 hour clock with now.hour % 12 instead of now.hour.