Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert datetime.date to datetime.datetime?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'

>Solution :

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:


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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading