Now & Today
As you can see, the methods now() and today() will give the same results.
The difference is that now() can take a timezone as an argument, and today doesn’t.
>>> import datetime >>> now = datetime.datetime.now() >>> today = datetime.datetime.today() >>> now datetime.datetime(2017, 4, 17, 17, 14, 10, 481635) >>> today datetime.datetime(2017, 4, 17, 17, 14, 18, 970121)
Combine Date &Time
Combine lets us combine a date and a time.
Let’s consider that Today should represent a date at midnight
import datetime now = datetime.datetime.now() today = datetime.datetime.today() realistic_today = datetime.datetime.combine(datetime.date.today(), datetime.time()) print("Now: {}".format(now)) print("Today: {}".format(today)) print("A Realistic Today: {}".format(realistic_today))
OUTPUT:
Now: 2017-04-17 14:33:09.245782
Today: 2017-04-17 14:33:09.245799
A Realistic Today: 2017-04-17 00:00:00
If no values were given as arguments to datetime.time(),
it will return the default values set for hour, minute and second which is 0 for each (i.e. datetime.datetime(2017, 4, 17, 0, 0) )
Testing the Realistic Today
>>> realistic.year 2017 >>> realistic.month 4 >>> realistic.hour 0 >>> realistic.weekday() 0 >>> now.timestamp() 1492438450.481635
Monday is 0.
1492438450.481635 is your local system time.
Exercise
Write a function named minutes
that takes two datetime
s and, using timedelta.total_seconds()
to get the number of seconds, returns the number of minutes, rounded, between them. The first will always be older and the second newer. You’ll need to subtract the first from the second.
import datetime def minutes(before, after): interval = after - before intv_minutes = round(interval.total_seconds()/60) return intv_minutes