Dates and Times
Contents
Dates and Times#
Dealing with dates and times is vital to many programming tasks from something as simple as displaying the current date and time to pulling up all of the records that were created during a particular period of time.
Dates and times have a surprising amount of complexity, between timezones, daylight savings times, leap years, and varying month lengths. Luckily modern Python programmers don’t need to figure this all out, but instead can rely on libraries to handle to package it into a few (relatively) simple types.
Table of Contents
Part 1: Datetime objects#
The datetime
module provides types for manipulating dates and times. In this
lesson we’ll learn about the datetime
type.
Part 1.1: The current date and time#
To get the current date and time, first you’ll need to import the datetime
type from the datetime
module. Then you can call the .today()
method, which
will return a datetime
object with the current date and time.
from datetime import datetime
now = datetime.today()
Part 1.2: Simple date and time formatting#
If you want to display a human-readable date or time, you can convert a
datetime object to a string using the str
type.
print(str(now))
2024-04-16 22:20:33.420391
For just the date or time, you can call the .date()
or .time()
methods
respectively, then convert the returned value to a string.
print(str(now.date()))
print(str(now.time()))
2024-04-16
22:20:33.420391
Part 1.3: Individual values#
You can access individual parts of a datetime
object via the following
properties:
year
month
day
hour
minute
second
microsecond
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)
2024
4
16
22
20
33
420391
To get the day of the week you can call the .weekday()
method. It will return
an integer between 0
and 6
representing Monday
through Sunday
.
print(now.weekday())
1
For a list-like iterable of day names in the correct order, you can import
day_name
from the calendar
module.
from calendar import day_name
print(list(day_name))
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
You can then use the value returned by the .weekday()
method as the index
value of day_name
to get the weekday name.
print(day_name[now.weekday()])
Tuesday
Part 1.4: Getting a specific date#
To create a datetime
object with some other date and time, call the
datetime
type and pass integer arguments for at least the year
, month
and
day
.
In this example, I’m making a datetime
object for the date of the initial
release of Python1.
datetime(1991, 2, 20)
datetime.datetime(1991, 2, 20, 0, 0)
You can also optionally also pass the hour
, minute
, second
and
microsecond
.
datetime(1991, 2, 19, 10, 35, 26)
datetime.datetime(1991, 2, 19, 10, 35, 26)
Part 2: Date formatting#
Since there are so many ways to represent a date or time, most programming
languages provide a fairly standard set of date formatting codes, where
each code is a character prefixed by a %
that is used to represent a
particular field and presentation.
These can then be put together in a string to indicate a how a date should be displayed or interpreted.
For example, the string "%Y-%m-%d %H:%M:%S"
would represent a date like
"1991-02-19 10:35:26"
.
For a full list of format codes see the format codes table in the reference section of this page.
Part 2.1: Displaying#
To display a date in a particular format, use the .strftime()
method on a
datetime
object, and pass it a string with the date format you wish to use.
print(now.strftime('%Y-%m-%d %H:%M:%S'))
2024-04-16 22:20:33
Part 2.2: Interpreting#
If you have a date string that you want to turn into a datetime
object, use
the .strptime()
method on the datetime
type. Pass it two arguments: the
date string and the format string.
datetime.strptime("6/5/20", "%m/%d/%y")
datetime.datetime(2020, 6, 5, 0, 0)
Part 3: Relative dates and times#
When working with dates and times we often care about the amount of time since or until a particular date, or the times between two dates and times.
Part 3.1: Durations#
Python provides the timedelta
type to represent a duration of time, which you
can import from the datetime
module.
To construct a timedelta
object, pass a keyword argument with an integer
value for any of the following:
days
seconds
microseconds
milliseconds
minutes
hours
weeks
For example, to make a timedelta
object representing a quarter hour you would
pass minutes=15
.
from datetime import timedelta
timedelta(minutes=15)
datetime.timedelta(seconds=900)
You can also do math with timedelta
objects.
week = timedelta(weeks=1)
fortnight = timedelta(days=14)
fortnight / week
2.0
While timedelta
objects can be created in any of the above units of
measurement, they are stored in days
and seconds
. For example, here we
create a moment
timedelta of 1
minute and 30
seconds.
moment = timedelta(minutes=1, seconds=30)
This is stored as 90
seconds.
print(moment.seconds)
90
delta = timedelta(days=1, hours=12)
print(delta.days)
print(delta.seconds)
1
43200
Part 3.2: Adding and subtracting from dates#
week = timedelta(days=7)
last_week = now - week
print("last week:", last_week)
last week: 2024-04-09 22:20:33.420391
tomorrow = now + timedelta(days=1)
print("tomorrow:", tomorrow)
tomorrow: 2024-04-17 22:20:33.420391
Part 3.3: Difference between dates#
birthday = datetime(2020, 6, 5)
age = now - birthday
print(age)
1411 days, 22:20:33.420391
Reference#
Format Codes#
Code(s) |
Field |
Example |
Format details |
|
---|---|---|---|---|
|
Weekday |
|
abbreviated name |
|
|
Weekday |
|
full name |
|
|
Weekday |
|
as number, Monday=1 (Solars: Sunday=1) |
|
|
Weekday |
|
as number, Sunday=0 |
|
|
|
Month |
|
abbreviated name |
|
Month |
|
full name |
|
|
Month |
|
as number, zero-padded |
|
|
Day of Month |
|
as number, zero-padded |
|
|
|
Day of Month |
|
as number |
|
|
Year |
|
two digit |
|
|
Year |
|
four digit |
|
|
Hour |
|
24-hour clock, zero-padded |
|
|
Hour |
|
24-hour clock |
|
Minute |
|
minute |
|
|
Second |
|
second |
|
|
Microsecond |
|
zero-padded microsecond |
|
|
Time Period |
|
AM or PM |
|
|
Timezone |
|
name |
|
|
Timezone |
|
abbreviation |
|
|
Epoch Seconds |
|
epoch timestamp |
|
|
Day of Year |
|
zero-padded number, up to 366 |
|
|
Century |
|
number (first two digits of year) |
|
|
Week of Year |
|
year starts at first Monday |
|
|
Week of Year |
|
year starts at first Sunday |
|
|
Week of Year |
|
year starts at first Monday with 4+ days |
|
|
Date and Time |
|
preferred |
|
|
Date and Time |
|
national |
|
|
Date |
|
same as %Y-%m-%d |
|
|
Date |
|
same as %m/%d/%y |
|
|
Date |
|
preferred |
|
|
Time |
|
12 hour notation |
|
|
Time |
|
%H:%M:%S |
|
|
Time |
|
24 hour notation |
|
|
Time |
|
preferred |
|
|
Character |
|
newline |
|
|
Character |
|
tab |
|
|
Character |
|
literal % |
See also#
Glossary#
Dates#
- date formatting codes#
A set of characters prefixed by
%
which represent a particular date or time field and presentation. For example"%m"
is for the month as a number01
-12
while"%M"
is for the full month name and"%b"
is for the abbreviated month name.- timestamp#
- epoch timestamp#
- unix timestamp#
A representation of a particular point in time as an integer, the number of seconds since Jan 01 1970 UTC.
- 1
https://groups.google.com/g/alt.sources/c/O2ZSq7DiOwM/m/gcJTvCA27lMJ?pli=1