calculate dates in python - 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

Related

get the start and end timestamp of the current week in python

I need to get the timestamps in milliseconds based on the current day. The start timestamp must be Monday 00:00 (start of the day of the current week) and the end timestamp should be the end of the week which in my case ends with Friday 23:59. I have an implementation that does not give the timestamps from 00:00 to 23:59 maybe you can help me change my solution
.
from datetime import date, datetime, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=4)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
You can use datetime.replace():
from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
output
Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Start with a datetime to include time fields, but create it only from the year, month, day values of the date.today().
Subtract the current weekday to get to Monday 0:0:0.
Add 5 days to get to Saturday 0:0:0 and subtract 1 minute to get to Friday 23:59:00.
from datetime import date, datetime, timedelta, time
# use a datetime to get the time fields but init it just with a date to default to 0:0:0
today = datetime(date.today().year, date.today().month, date.today().day)
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=5) - timedelta(minutes=1)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
Output:
Today: 2021-07-08 21:55:41.062506
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Something like this works:
from datetime import date, datetime, time
today = date.today()
week_start = datetime(today.year,
today.month,
today.day - today.weekday())
week_end = datetime(today.year,
today.month,
today.day + 7 - today.weekday(),
time.max.hour,
time.max.minute,
time.max.second,
time.max.microsecond)
print(week_start, week_end)
It gives:
2021-07-05 00:00:00 2021-07-11 00:00:00

Compare QDateTime

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.

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

Datetime: Check if date is in 1 week

What I am trying to do is see if date is in 1 week from currdate
from datetime import datetime, timedelta
import yagmail
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
currdate = '{}-{}-{}'.format(year, month, day)
currdate = datetime.strptime(currdate, '%Y-%m-%d')
date = '2018-04-01'
days = currdate - timedelta(int(date[-2:]))
days = str(days)
print(days)
if days[8:11] == '07':
yag = yagmail.SMTP("##########gmail.com", "######")
content = ['One Of Your Homework\'s Is Due In 1 Week!']
yag.send('###########gmail.com', 'Homework Due Soon!', content)
else:
print('It Isn\'t')
But it prints:
2018-04-07 00:00:00
It Isnt't
And I'm not sure why. Because days[8:11] is 07.
It is not 07. It's 07 (note the trailing space).
The following change will work:
if int(days[8:11]) == 7:
I'd create a function that you pass the date as a string. Something like this:
import datetime
def check_if_less_than_seven_days(x):
d = datetime.datetime.strptime(x, "%Y-%m-%d") # Add .date() if hour doesn't matter
now = datetime.datetime.now() # Add .date() if hour doesn't matter
return (d - now).days < 7
if check_if_less_than_seven_days("2018-04-18"):
print('Do something') # This will not print
if check_if_less_than_seven_days("2018-04-14"):
print('Do something') # This will print
Will print:
'Do something'
I suppose your first line when you initiate datetime.now() three times is just for testing purposes but dont do this as it could end up over different days (if you run this exactly at the milliseconds around midnight..) this will work better in that regard.
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
Anyway, read up on datetime timedelta. Just make you logic around that.
https://docs.python.org/3/library/datetime.html#timedelta-objects
import datetime
test_date_string = "2018-04-10"
d = datetime.datetime.strptime(test_date_string, "%Y-%m-%d")
now = datetime.datetime.now()
delta = d - now
elif delta.days < 7:
print("You have less then 7 days to go")
For days[8:11] you get the following output
>>> days[8:11]
'08 '
So you should use days[8:10]=='07' in case you want to use the same method,as it wont have extra space at the end.
>>> days[8:10]
'08'
so you should use
if days[8:10] == '07':

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)

Categories

Resources