How can I compare a date and a datetime in Python? - python

Here's a little snippet that I'm trying execute:
>>> from datetime import *
>>> item_date = datetime.strptime('7/16/10', "%m/%d/%y")
>>> from_date = date.today()-timedelta(days=3)
>>> print type(item_date)
<type 'datetime.datetime'>
>>> print type(from_date)
<type 'datetime.date'>
>>> if item_date > from_date:
... print 'item is newer'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.date
I can't seem to compare the date and the datetime values. What would be the best way to compare these? Should I convert the datetime to date or vice-versa? How do i convert between them.
(A small question but it seems to be a little confusing.)

Use the .date() method to convert a datetime to a date:
if item_date.date() > from_date:
Alternatively, you could use datetime.today() instead of date.today(). You could use
from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)
to eliminate the time part afterwards.

I am trying to compare date which are in string format like '20110930'
benchMark = datetime.datetime.strptime('20110701', "%Y%m%d")
actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")
if actualDate.date() < benchMark.date():
print True

Here is another take which preserves information in case both the inputs are datetimes and not dates, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:
datetime.datetime(d.year, d.month, d.day)
Suggestion:
from datetime import datetime
def ensure_datetime(d):
"""
Takes a date or a datetime as input, outputs a datetime
"""
if isinstance(d, datetime):
return d
return datetime.datetime(d.year, d.month, d.day)
def datetime_cmp(d1, d2):
"""
Compares two timestamps. Tolerates dates.
"""
return cmp(ensure_datetime(d1), ensure_datetime(d2))

In my case, I get two objects in and I don't know if it's date or timedate objects. Converting to date won't be good as I'd be dropping information - two timedate objects with the same date should be sorted correctly. I'm OK with the dates being sorted before the datetime with same date.
I think I will use strftime before comparing:
>>> foo=datetime.date(2015,1,10)
>>> bar=datetime.datetime(2015,2,11,15,00)
>>> foo.strftime('%F%H%M%S') > bar.strftime('%F%H%M%S')
False
>>> foo.strftime('%F%H%M%S') < bar.strftime('%F%H%M%S')
True
Not elegant, but should work out. I think it would be better if Python wouldn't raise the error, I see no reasons why a datetime shouldn't be comparable with a date. This behaviour is consistent in python2 and python3.

Create and similar object for comparison works too
ex:
from datetime import datetime, date
now = datetime.now()
today = date.today()
# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
print(True)
two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
print("this will work with datetime too")

I got you bro
you can use timetuple function to compare between date obj and datetime obj
>>> from datetime import datetime
>>> date_obj=datetime.utcnow().date()
>>> type(date_obj)
<type 'datetime.date'>
>>> datetime_obj=datetime.utcnow()
>>> type(datetime_obj)
<type 'datetime.datetime'>
>>> datetime_obj.timetuple()
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=2, tm_min=12, tm_sec=43, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> date_obj.timetuple()
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=284, tm_isdst=-1)
>>> type(datetime_obj.timetuple())
<type 'time.struct_time'>
>>> type(date_obj.timetuple())
<type 'time.struct_time'>
>>> date_obj.timetuple()<datetime_obj.timetuple()
True

Related

How to change a datetime format in python?

How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04

Python how to save datetime.strptime in datetime.time format

So I was trying to make a simple code using datetime and came across an error.
import time
from datetime import datetime
x = True
b = datetime.strptime("06:10", "%H:%M")
while x == True:
a = datetime.now().time()
print(a)
if a > b:
x = False
time.sleep(0.945)
As a result I get
TypeError: unorderable types: datetime.time() > datetime.datetime()
So I was wondering if it's possible to save a datetime.strptime in the datetime.time() format.
Thanks in advance
You tried to compare a datetime and time object, which Python won't let you compare.
If you do datetime.strptime() you get an object which holds a date and time (called datetime). But because you do not also parse the date it defaults to 01-01-1900. Now datetime.now() also gets you a datetime object but with the current date. So directly comparing datetime.now() and b won't work because the dates are different.
Now you already use the current time only by doing datetime.now().time(), so you also need to apply that to b by doing b = b.time() somewhere before the comparison.
use 'datetime.now()' insted of 'datetime.now().time()'
Compare .time() of both a and b as:
if a > b.time(): # if you want to compare only time
and not the datetime objects. Reason at the end of the answer.
datetime.now().time() is of datetime.time type:
>>> type(datetime.now().time())
<type 'datetime.time'>
whereas, datetime.strptime() and datetime.now() are of datetime.datetime type:
>>> type(datetime.strptime("06:10", "%H:%M"))
<type 'datetime.datetime'>
>>> type(datetime.now())
<type 'datetime.datetime'>
Edit based on comment from Martijn.
On creating datetime object like datetime.strptime("06:10", "%H:%M") date will be set as 1900-01-01. And definitely I dont't think you want to compare with that. You may check the date as:
>>> d = datetime.strptime("06:10", "%H:%M")
>>> d
datetime.datetime(1900, 1, 1, 6, 10)

How to subtract datetimes / timestamps in python

Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:
2015-08-10 19:33:27.653
2015-08-10 19:31:28.209
How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.
Parse your strings as datetime.datetime objects and subtract them:
from datetime import datetime
d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")
print(d1 - d2)
Gives me:
0:01:59.444000
Also check out timedelta documentation for all possible operations.
you can do subtraction on 2 datetime objects to get the difference
>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10
convert your strings to datetime objects with time.strptime
datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
timedelta.seconds does not represent the total number of seconds in the timedelta, but the total number of seconds modulus 60.
Call the function timedelta.total_seconds() instead of accessing the timedelta.seconds property.
For python 3.4, first you'd need to convert the strings representing times into datetime objects, then the datetime module has helpful tools work with dates and times.
from datetime import datetime
def to_datetime_object(date_string, date_format):
s = datetime.strptime(date_string, date_format)
return s
time_1 = '2015-08-10 19:33:27'
time_2 = '2015-08-10 19:31:28'
date_format = "%Y-%m-%d %H:%M:%S"
time_1_datetime_object = to_datetime_object(time_1, date_format)
time_2_datetime_object = to_datetime_object(time_2, date_format)
diff_time = time_1_datetime_object - time_2_datetime_object

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Converting datetime to strptime

I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).

Categories