Python Date & Time

Python provides date and time related functions in datetime module. There are 5 classes in datetime module.

  • datetime
  • date
  • time
  • timedelta
  • tzinfo

datetime

datetime class stores both date and time data. To access date and time related methods from this class, you should import datetime class from the datetime module.

To get the current date and time, you can use now() function.

from datetime import datetime
now = datetime.now()
print(now)               # 2020-01-20 13:16:26.020192

To format a date as string you can use strftime() method. strftime stands for string format time. Format directives are used to format datetime objects in Python.

%Y directive represents year, %m represents month as number, %d represents the day of month and %B represents month as string name.

You can find full list of strftime() format directives at the end of this page (Python strftime()/strptime() format directives).

from datetime import datetime

date = datetime(2020, 1, 20)
print(date.strftime("%Y-%m-%d"))           # 2020-01-20
print(date.strftime("%d %B %Y"))           # 20 January 2020

You can also parse a string and create datetime object using strptime() method. strptime stands for string parse time.

To format s string, you can use the same format directives as strftime (Python strftime()/strptime() format directives).

from datetime import datetime

date = datetime.strptime("2020-01-20", "%Y-%m-%d")
date = datetime.strptime("20 January 2020", "%d %B %Y")

date

date class only stores date information. To access methods from this class, you should import date class from the datetime module.

To find the current date, you can use today() method.

from datetime import date

today = date.today()
print(today)                      # 2020-01-20

To find the number of days between two dates, you can subtract one date from the other.

from datetime import date

date1 = date(2020, 1, 20)
date2 = date(2008, 12, 3)
diff = date1 - date2
print(str(diff.days) + " days")           # 4065 days

time

time class only stores time information. To access methods from this class, you should import time class from the datetime module.

You can use combine() method to create a datetime object from a date and a time object.

from datetime import date
from datetime import time

date1 = date(2020, 1, 20)
time1 = time(14, 27, 30)
datetime = datetime.combine(date1, time1)
print(datetime)          # 2020-01-20 14:27:30

timedelta

timedelta class stores information about the duration of time.

You can define timedelta as weeks, days, hours, minutes, seconds, milliseconds and microseconds.

from datetime import timedelta

delta = timedelta(weeks=7)
print(delta)                       # 49 days, 0:00:00

You can use timedelta object to make calculations on dates.

from datetime import timedelta
from datetime import datetime

current_time = datetime.now();
delta = timedelta(weeks=7, days=5, hours=3)

# first prints current date and time
# then prints date and time after delta (weeks, days,...)
print(current_time)                      # 2020-01-20 14:15:24
print(current_time + delta)              # 2020-03-14 17:15:24

tzinfo

A datetime object is naive by default. A naive datetime object does not contain timezone information. tzinfo class in datetime module is an abstract class (it is not implemented in datetime module).

from datetime import datetime

naive = datetime.now()
print(naive.tzinfo)          # None
                             # datetime instance does not contain
                             # a timezone information by default

To include timezone information in a datetime instance, you need an implementation for tzinfo class. The third-party pytz module provides a simple implementation of tzinfo. After creating a timezone instance, you need to call localize() method to convert a naive datetime to aware datetime.

from datetime import datetime

naive = datetime.now()
timezone = pytz.timezone("US/Eastern")
aware = timezone.localize(naive)
print(aware.tzinfo)                      # US/Eastern

Python strftime()/strptime() format directives

DirectiveMeaningExample
%aAbbreviated weekday nameMon, Tue, Wed
%AFull weekday nameMonday, Tuesday, Wednesday
%wDay of week (0-6).
0 is Sunday , 6 is Saturday
0, 1, 2, 3, 4, 5, 6
%dDay of month (01-31)01, 02, …, 31
%bAbbreviated month nameJan, Feb, Mar
%BFull month nameJanuary, February, March
%mMonth as zero-padded number (01-12)01, 02, …, 12
%yYear without century01, 02, …, 99
%YYear with century2001, 2002, 2099, …
%HHour (24-hour clock)00, 01, …, 23
%IHour (12-hour clock)1, 2, …, 12
%pAM or PMAM, PM
%MMinute (00-59)00, 01, …, 59
%SSecond (00-59)00, 01, …, 59
%fMicrosecond (000000-999999)000000, 000001, …, 999999
%zUTC offset+0100, -0500
%ZTime zone nameUS/Eastern, CST, UTC
%jDay of the year (001-366)365
%UWeek number of the year (Sunday as the first day of the week)00, 01, …, 53
%WWeek number of the year (Monday as the first day of the week)00, 01, …, 53
%cDate and time in locale formatThu Dec 31 14:30:05 2020
%xDate in locale format12/31/20
%XTime in locale format14:30:05
%%Literal ‘%’ character%
SHARE