Working with Time
.. can be tricky to get your head around. Here are some code snippets to get you started. You'll need to import the library:
import datetime Get the current timeThe current time will be saved into a current_time object. An object is like a variable in that it contains data, But it can store lots of data and functions too ( you don't need to worry about this for GCSE).
current_time = datetime.datetime.now() Use a period to get the data from the object. The following code will give you the hour of the day: current_time.hour Get the minutes with the following code: current_time.minute |
Create a specific date
To store a specific date into a date object use the following code. The Start object will contain the 28th February 2024:
Start = datetime.date(2024,2,28)
Start = datetime.date(2024,2,28)
Find the time between two dates
You can subtract one date from another to find the time between them. This will be saved into a date object.
Start = datetime.date(2024,2,28)
End = datetime.date(2024,2,30)
Diff = End - Start
print( Diff.days) # prints 2 as there are two days between the dates.
End = datetime.date(2024,2,30)
Diff = End - Start
print( Diff.days) # prints 2 as there are two days between the dates.