Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating if date is in start, future or present in Python

I have two date/time strings:

start_date = 10/2/2010 8:00:00  

end_date = 10/2/2010 8:59:00

I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work.

I've not really done much time based calculations in Python so any help would be really appreciated!

Many thanks

like image 509
kron Avatar asked Sep 04 '10 15:09

kron


People also ask

How does Python calculate future time?

You can create a timedelta by passing any number of keyword arguments such as days, seconds, microseconds, milliseconds, minutes, hours, and weeks to timedelta() . Once you have a timedelta object, you can add or subtract it from a datetime object to get a datetime object relative to the original datetime object.


1 Answers

from datetime import datetime
start_date = "10/2/2010 8:00:00"
end_date = "10/2/2010 8:59:00"

# format of date/time strings; assuming dd/mm/yyyy
date_format = "%d/%m/%Y %H:%M:%S"

# create datetime objects from the strings
start = datetime.strptime(start_date, date_format)
end = datetime.strptime(end_date, date_format)
now = datetime.now()

if end < now:
    # event in past
elif start > now:
    # event in future
else:
    # event occuring now
like image 154
Richard Fearn Avatar answered Sep 28 '22 11:09

Richard Fearn