1

in below I got datetime.date and datetime.datetime class.


start=df.index[0]
start_input_1=datetime.strptime(start_input[:10],'%Y-%m-%d')

print(start_input[:10])    
print(type(start))
print(type(start_input_1))

2021-09-01
<class 'datetime.date'>
<class 'datetime.datetime'>

Now if I below comparison, then I got an error of

cannot compare datetime.datetime to datetime.date

if start_input_1>=start:
        start_plot=start_date_input_1

so how do I convert datetime.date into datetime.datetime so I can compare two dates?

if I use pd.to_datetime(), it is converted to timestamp instead of datetime. Thanks for your help.

start=pd.to_datetime(start)
print(start)

class 'pandas._libs.tslibs.timestamps.Timestamp'

roudan
  • 3,082
  • 5
  • 31
  • 72
  • Does this answer your question? [Convert date to datetime in Python](https://stackoverflow.com/questions/1937622/convert-date-to-datetime-in-python) – Jimmar Jun 14 '22 at 21:07

1 Answers1

2

You can either check if dates are the same by taking date from the datetime object, or add default time (00:00:00) to the date object to make it datetime:

from datetime import datetime, date

dt = datetime.fromisoformat("2020-01-01T10:00:00")
d = date.fromisoformat("2020-01-01")

print(dt, d)  # 2020-01-01 00:00:00 2020-01-01
print(type(dt), type(d))  # <class 'datetime.datetime'> <class 'datetime.date'>

# Check only by date, do not check time
if d == dt.date():
    print("Same date")

# Check by date, but both have to be 00:00:00
d = datetime.fromisoformat(d.isoformat())
if d == dt:
    print("Same date and 00:00:00")
  • how to check if it is a datetime.date type? I used add default time (00:00:00) to the date object to make it datetime and it is False. – roudan Jun 14 '22 at 21:42
  • When you add time, you are initialize another object, which is already `datetime`, not `date`. To avoid this, you can try comparing `datetime.fromisoformat(d.isoformat())` to `dt` directly, instead of saving it to `d`. – German Ivanov Jun 14 '22 at 22:04