Can't seem to subtract dates in Python: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' - python

Code is below, I am simply trying to subtract 2 dates, and figure out if the date difference meets a certain threshold. Can't seem to figure out how to get them in the right format for this.
def activity_breakup():
now = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S')
print("now is equal to {}".format(now))
for activity in convert_csv_to_list()[1:]:
date = datetime.datetime.strptime(activity[2], '%m/%d/%Y')
print("date is equal to {}".format(date))
if now - date == 0:
activities_in_next_7_days.append(activity)
elif now - date <= 7:
activities_today.append(activity)
else:
continue
Output of the prints are:
now is equal to 2018-04-17 00:00:00
date is equal to 2018-04-22 00:00:00

strftime returns a string object (think: string from time).
strptime returns a date object (think: string parse time).
Looking at your code, now is a string and date is a date object. The error indicates this as well.
If you want to compare dates, change the type of now.
def activity_breakup():
now = datetime.date.today()
print("now is equal to {}".format(now.strftime('%Y-%m-%d %H:%M:%S')))
for activity in convert_csv_to_list()[1:]:
date = datetime.datetime.strptime(activity[2], '%m/%d/%Y')
print("date is equal to {}".format(date))
if now - date == 0:
activities_in_next_7_days.append(activity)
elif now - date <= 7:
activities_today.append(activity)
else:
continue
On an unrelated note, perhaps now - date is supposed to return the number of days? Currently it's returning a datetime.timedelta object. You can do the following:
days_diff = (now - date).days
if days_diff == 0:
activities_in_next_7_days.append(activity)
elif days_diff <= 7:
activities_today.append(activity)
else:
continue

Try using a datetime object instead of a string in your first statement:
from datetime import datetime
now = datetime.today()
The last portion of your corresponding line is just to convert it to a string with a specific format.

stftime returns a string while strptime returns a datetime object. Just move the strftime into string formatting.
def activity_breakup():
# now is a datetime now
now = datetime.date.today()
print("now is equal to {}".format(now.strftime('%Y-%m-%d %H:%M:%S')))
for activity in convert_csv_to_list()[1:]:
date = datetime.datetime.strptime(activity[2], '%m/%d/%Y')
print("date is equal to {}".format(date))
if now - date == 0:
activities_in_next_7_days.append(activity)
elif now - date <= 7:
activities_today.append(activity)
else:
continue

Related

Python: How to see if a unix timestamp is before or after a time of day

I'm trying to figure out if a unix timestamp is after 21:00. However, I'm having type errors.
This is my code:
from datetime import datetime, time
theTime=1497204737
the_date = (
datetime.fromtimestamp(
int(theTime)
).strftime('%H:%M:%S')
)
if the_date >= time(21,00):
print("we did it!")
I keep getting this error:
TypeError: '<=' not supported between instances of 'str' and 'datetime.time'
How can I fix this issue?
The problem is that you convert the timestamp to a datetime but then you convert it to a string again:
>>> the_date = datetime.fromtimestamp(int(theTime)).strftime('%H:%M:%S')
>>> type(the_date)
str
There are several ways to make it work:
For example you could simply keep the timestamp as datetime and compare the hours:
from datetime import datetime, time
theTime=1497204737
the_date = datetime.fromtimestamp(int(theTime))
if the_date.hour >= 21:
print("we did it!")
or convert the datetime to a time and compare the times:
if time(the_date.hour, the_date.minute) >= time(21, 0):
print("we did it!")

Trying to subtract two dates to find number of days inbetween

Within Zapier, I have two dates and am trying to find the number of days between them in a Code Step. I run a Formatter Step on each date to output a datetime object in YYYY-MM-DD then run the following code below:
submit = input['submit_date']
event = input['event_date']
delta = event-submit
numdays = delta.days
return {'numdays': numdays}
The error I get suggests the two dates that i'm importing are strings, not datetimes.
Here is the error:
Your code had an error! Traceback (most recent call last): File "/tmp/tmp7xyg3Z/usercode.py", line 10, in the_function delta = event-submit TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'
Anyone know what i'm doing wrong or a better way to accomplish this task?
The formatter steps aren't included, but in general you are wanting time or datetime objects (import time or import datetime)
You should probably be looking at something like datetime.strptime(date_string, format) from the datetime option to take your text string and convert it to a date/time object.
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
I have 2 methods get_days(start_date, end_date) and increment_da_day(str_date)
invoke get_days() it returns you a list of days(format is yyyymmdd), you can provide your start date and end date and print the get_days(start_date, end_date) - 1
For example:
import datetime
def get_days(start_date, end_date):
"""returns a list of days"""
all_days = []
starts = start_date
all_days.append(starts)
while int(starts) < int(end_date):
starts = increment_a_day(starts)
all_days.append(starts)
return all_days
def increment_a_day(str_date):
"""increments a day for given date string in format yyyymmdd"""
year = int(str_date[:4])
month = int(str_date[4:6])
day = int(str_date[-2:])
now = datetime.date(year, month, day)
delta = datetime.timedelta(days=1)
return (now + delta).strftime('%Y%m%d') #yyyymmdd
You only need to do following:
days = get_days("20160601", "20160602")
delta = len(days) - 1
print delta
if they are strings the you can either pass input or take the input right there, the following code will return the days
def h():
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(input('Enter first date in MM/DD/YY format '), date_format)
b = datetime.strptime(input('Enter second date in MM/DD/YY format '), date_format)
delta = b - a
print (delta.days)
return int(delta.days)
or
a='8/18/2008'
b='9/26/2008'
def h(c,d):
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(c, date_format)
b = datetime.strptime(d, date_format)
delta = b - a
print (delta.days)
return int(delta.days)

Converting string to datetime then comparing it with datetime.now

I want to take a string
"9:09am Jan 23"
and compare it with datetime.now() to get the amount of difference in hours only.
So if I did something like
now = datetime.datetime.now()
if now - (string in hours) > 24:
return True
else:
return False
I've been messing with it for a little while and cant seem to successfully compare a string (or converted string object) with datetime.now.
You can convert the string to datetime using strptime in conjunction with the relevant format. You'll need to add the current year though:
import datetime
now = datetime.datetime.now()
year = now.year
datestring = "9:09am Jan 23 " + year
dt = datetime.datetime.strptime(datestring, "%H:%M%p %b %d %Y")
Subtracting two datetimes gives you a timedelta object, so you'll need to extract the days:
diff = now - dt
days_diff = diff.days
Here is a function that will grab two instances of current time and return the difference in seconds. This is done mostly with datetime's 'strptime', in which I convert the current time to strings. If you want to ditch the current time, replace the 'time' or 'xvar' variables with a string. I used seconds here, but you can return hours of difference just as easily.
import datetime, sys
def time_passed():
while True:
inp = raw_input("Press [Y] to start, or [X] to exit.: ").lower()
if inp == 'y':
now = datetime.datetime.now()
xvar = now.strftime("%b %d %H:%M:%S")
time = datetime.datetime.strptime(xvar, "%b %d %H:%M:%S")
time = time.replace(year = 2016)
print "The first recording of the time is: {0}".format(time)
print "The second recording of the time is: {0}".format(now)
yvar = (now - time)
print "Between the two times, there is a difference of {0} seconds".format(yvar.total_seconds())
continue
elif inp == 'x':
sys.exit()
break
else:
print "Command Error!"
continue
if __name__ == '__main__':
time_passed()
Thanks for the help guys! What I wanted was how to compare the hours only, so I did a little hacking. What I needed to do was get
diff = now - dt
then to get the hours of that, which is what I was stuck on. The solution was to get the seconds of diff and divide by 3600.
My solution: a function that takes a string time and hour param to determine which messages to delete. (writing a web automation script)
def to_delete(self, date, accepted_range):
""" decides to delete a message based on certain criteria """
now = datetime.datetime.now()
date_str = "%s %s" % (date, now.year)
dt = datetime.datetime.strptime(date_str, "%H:%M%p %b %d %Y")
diff = now - dt
if diff.seconds/3600 > accepted_range:
return True
else:
return False
It gives me the hours only and now I can delete posts if they're over x hours old

How to subtract today's date with an input date?

My current code:
import datetime
from time import strptime
leapyear = 0
isValid = False
while not isValid:
in_date = input(" Please in put a year in the format dd/mm/yyyy ")
try:
d = strptime(in_date, '%d/%m/%Y')
isValid=True
except:
print ("This is not in the right format")
diff = d -datetime.date.today()
print(in_date)
print(d)
print(diff)
I cannot subtract the two dates, the input date and today's date from each other. It throws a TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.date' exception.
Any ideas why?
The datetime module objects only support subtraction with other objects from the same library. The time module struct_time tuple is not one of those.
Use the datetime.datetime.strptime() class method to parse the date instead:
d = datetime.datetime.strptime(in_date, '%d/%m/%Y')
then use the datetime.date() method to extract just a date object from the result:
diff = d.date() - datetime.date.today()
The result is a datetime.timedelta instance.
Don't catch all exceptions; catch just those thrown by strptime() when passed a string that doesn't match the expected format, ValueError:
while True:
in_date = input(" Please in put a year in the format dd/mm/yyyy ")
try:
d = datetime.datetime.strptime(in_date, '%d/%m/%Y').date()
break
except ValueError:
print ("This is not in the right format")
I used break here to end the while loop rather than use a flag variable.

How do i convert a date string from user input to date.today() python

Python newbie, i need to convert a string from a user input in the format dd/mm/yyyy and check to see if it is in the future?, will i need to re order the format of the input for comparison and convert it to a date object.
Not sure what you're specifically wanting to do, this will take in dd/mm/yyyy and tell you if it's older than now.
import time
# Get input
date = input("Enter a date: ")
# Convert to timestamp
date_timestamp = time.mktime(time.strptime(date, "%d/%m/%Y"))
# Check if in future
if(date_timestamp > time.time()):
print("It's in the future,")
else:
print("It's not in the future,")
from datetime import datetime, timedelta
today = datetime.date(datetime.today())
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
date_strings = [d.strftime('%d/%m/%Y') for d in (today, yesterday, tomorrow)]
for date_string in date_strings:
print datetime.date(datetime.strptime(date_string, '%d/%m/%Y')) > today
Ouputs:
False
False
True

Resources