简体   繁体   中英

Python date conversion and checking

I want to be able to convert string to date and then do operation to check if it's before or after a certain date. Input format : d/m/yyyy

6/7/2018

I want to check if the date above is before today's date 10/11/2018

How do I go about doing this? This is what I have:

import datetime
dateInput= '10/11/2018' 
dateFormat = '%d/%m/%Y'
dateObj= datetime.datetime.strptime(dateInput, dateFormat )

How do I do the checking if it's before or after a certain date eg 10/11/2018 ?

Just use date1 > date2

$ cat timebomb.py
#!/bin/env python

import datetime

date_format = '%d/%m/%Y'
boom_time = datetime.datetime.strptime('10/11/2018', date_format )

start_day = '01/11/2018'
day = datetime.datetime.strptime(start_day, date_format )

while day < boom_time:
    print ("Tick Tock.")
    day += datetime.timedelta(days=1)

print ("BOOM")

Run it ...

$ ./timebomb.py
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
BOOM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM