Link to Slides
Download
Report
Transcript Link to Slides
Python – Dates and
Times
Working with time in Python
The module for handling time is called "datetime" it contains four
classes:
◦ date - year, month, and day
◦ time - hour, minute, second, microsecond, and timezone
◦ datetime - holds both date and time (see above)
◦ timedelta - holds a 'difference' in time between two of the above
Details here: https://docs.python.org/3.4/library/datetime.html
datetime.date
Two ways to construct:
◦ date(year, month, day)
◦ date.today()
You can get the data out through attributes:
◦ date.year, date.month, date.day
d = datetime.date(2000, 12, 15)
d.year # 2000
datetime.time
One constructor:
◦ time(hour, minute, second, microsecond) all are assumed 0
unless specified
You can get the data out through attributes:
◦ time.hour, time.minute, time.second, time.microsecond
t = datetime.time(14, 11, 56)
t.minute # 11
datetime.datetime
Two constructors:
◦ datetime(year, month, day, hour, minute, second, microsecond)
◦ datetime.now() gets the current date and time
You can get the data out through attributes:
◦ Combined attributes of date and time
dt = datetime.datetime.now()
dt.day # 8
dt.hour # 1
datetime.timedelta
One constructor:
◦ timedelta(days, hours, minutes, seconds, ...)
◦ Defaults to zero if arguments aren't supplied
◦ delta = datetime.timedelta(days=2) # Represents 2 days duration
You can use it to calculate datetimes:
◦ datetime.datetime.now() + delta # yields a date 2 days from now
import datetime
now = datetime.datetime.now()
birth = datetime.datetime(1988, 11, 1, 9) #Nov 1st, 1988 9AM
my_age = now - birth # age is a timedelta
legal_drinking_age = datetime.timedelta(days = (21 * 365))
is_legal_to_drink = my_age > legal_drinking_age
# Doesn't take leap days/seconds into account
Converting Python datetime to ISO 8601
All the datetime classes have a "strftime" method
◦ This method will output a string formatted according to a pattern
dt = datetime.datetime(2015, 3, 4, 12, 35)
dt.strftime("%Y-%m-%d %H:%M:%S")
# yields '2015-03-04 12:35:00'
You can use the datetime class method, "strptime", to convert a string to
a datetime object.
◦ The method takes a date_string and a format, and it returns a datatime object
dt2 = datetime.datetime.strptime('2015-03-04 12:35:00',
"%Y-%m-%d %H:%M:%S")
assert dt == dt2
Combining Python and SQLite datetimes
SQL databases can't hold Python objects, so you must convert them
to ISO 8601 and store the resulting TEXT.
◦ You can use the 'strftime' method to do this
On retrieving a date encoded as TEXT you can convert the string back
to a Python datetime class.
◦ You can use the 'strptime' method to do this
Note, using SQL date/time functions may alter the format (i.e. add
microsecond precision or timezone info) so you should refrain from
using them.