Converting dates and times to and from strings in Python datetime (strftime, strptime)

Money and Business

Python's standard library datetime can be used to process dates and times (dates, times and times). The methods strftime() and strptime(), which convert dates and times to and from strings, can be used to manipulate dates and times in a variety of formats.

It can also perform operations such as subtraction and addition. For example, you can easily calculate and get the date 10 days ago or 3 weeks from now, or the time 50 minutes from now.

First, we will describe the following classes of objects available in the datetime module.

  • datetime.datetime:Date and time (date and time)
  • datetime.date:Date
  • datetime.time:Time
  • datetime.timedelta:Time difference and elapsed time

The methods strftime() and strptime(), which convert date/time and string to each other, are also explained.

  • datetimeobject
    • datetime.now():Today's date, current time
    • datetimeObject Constructor
    • Converting a datetime object to a date object
  • dateobject
    • date.today():Today's date
    • Constructor for the date object
  • timeobject
    • Constructor for the time object
  • timedeltaobject
    • Subtract datetime and date objects to create timedelta objects.
    • Constructor for the timedelta object
    • Subtraction and addition using timedelta objects
  • strftime():Conversion from date and time to string
  • strptime():Conversion from string to date and time

Also included in the standard library is the calendar module, which generates calendars in plain text or HTML format.

datetime object

A datetime object is an object that has both date (year, month, day) and time (hour, minute, second, microsecond) information. You can access those information with the following attributes.

  • year
  • month
  • day
  • hour
  • minute
  • second
  • microsecond

datetime.now(): Today's date, current time

datetime.now() will give you a datetime object with today's date (the current date) and the current time.

import datetime

dt_now = datetime.datetime.now()
print(dt_now)
# 2018-02-02 18:31:13.271231

print(type(dt_now))
# <class 'datetime.datetime'>

print(dt_now.year)
# 2018

print(dt_now.hour)
# 18

Constructor for datetime object

It is also possible to generate datetime objects for arbitrary dates and times.

The constructor for the datetime object is as follows.

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

The following values are required and others can be omitted. If omitted, the default value is 0.

  • year
  • month
  • day
dt = datetime.datetime(2018, 2, 1, 12, 15, 30, 2000)
print(dt)
# 2018-02-01 12:15:30.002000

print(dt.minute)
# 15

print(dt.microsecond)
# 2000

dt = datetime.datetime(2018, 2, 1)
print(dt)
# 2018-02-01 00:00:00

print(dt.minute)
# 0

Converting a datetime object to a date object

A datetime object can be converted to a date object by the date() method, as described next.

print(dt_now)
print(type(dt_now))
# 2018-02-02 18:31:13.271231
# <class 'datetime.datetime'>

print(dt_now.date())
print(type(dt_now.date()))
# 2018-02-02
# <class 'datetime.date'>

date object

A date object is an object that contains information about a date (year, month, day). It can be accessed by the attributes year, month, and day.

date.today(): Today's date

The date object of the current date (today's date) can be obtained with date.today().

d_today = datetime.date.today()
print(d_today)
# 2018-02-02

print(type(d_today))
# <class 'datetime.date'>

print(d_today.year)
# 2018

Constructor for the date object

The constructor for the date object is as follows

date(year, month, day)

All are required and cannot be omitted.

d = datetime.date(2018, 2, 1)
print(d)
# 2018-02-01

print(d.month)
# 2

time object

The time object is an object that contains information about time (hours, minutes, seconds, and microseconds). It can be accessed using the attributes hour, minute, second, and microsecond.

Constructor for the time object

The constructor of the time object is as follows.

time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

All of them are optional, and if they are omitted, they are set to 0.

t = datetime.time(12, 15, 30, 2000)
print(t)
# 12:15:30.002000

print(type(t))
# <class 'datetime.time'>

print(t.hour)
# 12

t = datetime.time()
print(t)
# 00:00:00

timedelta object

The timedelta object is an object that represents the time difference between two dates and times, or the elapsed time. It has information in days, seconds, and microseconds, and can be accessed by the attributes days, seconds, and microseconds. It is also possible to get the total number of seconds using the total_seconds() method.

Subtract datetime and date objects to create timedelta object.

Subtracting datetime objects from each other yields a timedelta object.

td = dt_now - dt
print(td)
# 1 day, 18:31:13.271231

print(type(td))
# <class 'datetime.timedelta'>

print(td.days)
# 1

print(td.seconds)
# 66673

print(td.microseconds)
# 271231

print(td.total_seconds())
# 153073.271231

Subtraction of date objects from each other similarly yields a timedelta object.

Constructor for the timedelta object

The constructor of the timedelta object is as follows

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All of them are optional, and if they are omitted, they are set to 0.

Note that the timedelta object only holds the following information.

  • a number of days: days
  • number of seconds: seconds
  • microsecond count: microseconds

For example, the following two are equal

  • weeks=1
  • days=7
td_1w = datetime.timedelta(weeks=1)
print(td_1w)
# 7 days, 0:00:00

print(td_1w.days)
# 7

Subtraction and addition using timedelta objects

The timedelta object can be used with the datetime and date objects to perform operations such as subtraction and addition. For example, you can easily calculate and get the date one week ago or 10 days from now, or the time 50 minutes from now.

d_1w = d_today - td_1w
print(d_1w)
# 2018-01-26

td_10d = datetime.timedelta(days=10)
print(td_10d)
# 10 days, 0:00:00

dt_10d = dt_now + td_10d
print(dt_10d)
# 2018-02-12 18:31:13.271231

td_50m = datetime.timedelta(minutes=50)
print(td_50m)
# 0:50:00

print(td_50m.seconds)
# 3000

dt_50m = dt_now + td_50m
print(dt_50m)
# 2018-02-02 19:21:13.271231

It can also be used to calculate the number of days until a specific date.

d_target = datetime.date(2020, 7, 24)
td = d_target - d_today
print(td)
# 903 days, 0:00:00

print(td.days)
# 903

strftime(): Conversion from date and time to string

The strftime() method of datetime and date objects can be used to convert date and time (date and time) information into a string in any format format.

formatting code

See the official documentation below for available formatting codes.

The main formatting codes are listed below.

  • %d:Day of the month in decimal notation with zero filled.
  • %m:Month in decimal notation with zero filled.
  • %y:The last two digits of the year in zero-filled decimal notation.
  • %Y:Four digits of the year in decimal notation with zero filled.
  • %H:When expressed in decimal notation with zero filled (24-hour notation)
  • %I:When expressed in decimal notation with zero filled (12-hour notation)
  • %M:For decimal notation with zero filled.
  • %S:Seconds in decimal notation with zero filled.
  • %f:Microseconds (6 digits) in decimal notation with 0 filled.
  • %A:Name of the day of the week for the locale
  • %a:Name of the day for the locale (abbreviated form)
  • %B:Locale month name
  • %b:Locale month name (abbreviated form)
  • %j:Day of the year in decimal notation with zero fill.
  • %U:Week number of the year in decimal notation with zero fill (the week begins on Sunday)
  • %W:Week number of the year in decimal notation with zero fill (the week begins on Monday)

The following formatting codes for day and month names can be obtained in different strings depending on the locale.

  • %A
  • %a
  • %B
  • %b

There is also a dedicated method for ISO 8601 format strings.

Sample Code

print(dt_now.strftime('%Y-%m-%d %H:%M:%S'))
# 2018-02-02 18:31:13

print(d_today.strftime('%y%m%d'))
# 180202

print(d_today.strftime('%A, %B %d, %Y'))
# Friday, February 02, 2018

print('Day number (how many days in a year / January 1 is 001):', d_today.strftime('%j'))
print('Week number (the week starts on Sunday / New Year's Day is 00):', d_today.strftime('%U'))
print('Week number (the week begins on Monday / New Year's Day is 00):', d_today.strftime('%W'))
# Day number (how many days in a year / January 1 is 001): 033
# Week number (the week starts on Sunday / New Year's Day is 00): 04
# Week number (the week begins on Monday / New Year's Day is 00): 05

If you want to get a number instead of a string, just convert it to an integer with int().

week_num_mon = int(d_today.strftime('%W'))
print(week_num_mon)
print(type(week_num_mon))
# 5
# <class 'int'>

In combination with the timedelta object, it is easy to create, for example, a list of biweekly dates in any format.

d = datetime.date(2018, 2, 1)
td = datetime.timedelta(weeks=2)
n = 8
f = '%Y-%m-%d'

l = []

for i in range(n):
    l.append((d + i * td).strftime(f))

print(l)
# ['2018-02-01', '2018-02-15', '2018-03-01', '2018-03-15', '2018-03-29', '2018-04-12', '2018-04-26', '2018-05-10']

print('\n'.join(l))
# 2018-02-01
# 2018-02-15
# 2018-03-01
# 2018-03-15
# 2018-03-29
# 2018-04-12
# 2018-04-26
# 2018-05-10

Using the list comprehension notation is smarter.

l = [(d + i * td).strftime(f) for i in range(n)]
print(l)
# ['2018-02-01', '2018-02-15', '2018-03-01', '2018-03-15', '2018-03-29', '2018-04-12', '2018-04-26', '2018-05-10']

strptime(): Conversion from string to date and time

datetime strptime() can be used to create a datetime object from a date or time string. It is necessary to specify the formatting string corresponding to the original string.

There is also a dedicated method for ISO 8601 strings (Python 3.7 or later).

Sample Code

date_str = '2018-2-1 12:30'
date_dt = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M')
print(date_dt)
# 2018-02-01 12:30:00

print(type(date_dt))
# <class 'datetime.datetime'>

By using the strftime() method on the retrieved datetime object, you can represent the date and time in a different format than the original string.

print(date_dt.strftime('%Y-%m-%d %H:%M'))
# 2018-02-01 12:30

If you convert it to a datetime object, you can also perform operations with timedelta objects, so for example, you can generate a string of a date 10 days ago in the same format.

date_str = '2018-2-1'
date_format = '%Y-%m-%d'
td_10_d = datetime.timedelta(days=10)

date_dt = datetime.datetime.strptime(date_str, date_format)
date_dt_new = date_dt - td_10_d
date_str_new = date_dt_new.strftime(date_format)

print(date_str_new)
# 2018-01-22
Copied title and URL