11.4. Datetime Format

  • format(dt, '%Y-%m-%d')

  • f'Today is {dt:%Y-%m-%d}'

  • dt.strftime('%Y-%m-%d')

11.4.1. Formats

  • format(dt, '%Y-%m-%d')

>>> from datetime import datetime
>>>
>>>
>>> dt = datetime(1961, 4, 12, 6, 7)
>>>
>>> format(dt, '%Y')
'1961'
>>>
>>> format(dt, '%Y-%m-%d')
'1961-04-12'
>>>
>>> format(dt, '%d.%m.%Y')
'12.04.1961'
>>>
>>> format(dt, '%H:%M')
'06:07'
>>>
>>> format(dt, '%Y-%m-%d %H:%M')
'1961-04-12 06:07'
>>>
>>> format(dt, '%Y-%m-%d %H:%M:%S')
'1961-04-12 06:07:00'
>>>
>>> format(dt, '%B %d, %Y')
'April 12, 1961'

11.4.2. Parameters

  • Similar in almost all programming language

  • Some minor differences like in JavaScript minutes are i, not M

Table 11.2. Date and time parsing and formatting parameters

Directive

Example

Meaning

%a

Sun, Mon, ..., Sat

Weekday as locale's abbreviated name

%A

Sunday, Monday, ..., Saturday (en_US)

Weekday as locale's full name

%w

0, 1, ..., 6

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday

%d

01, 02, ..., 31

Day of the month as a zero-padded decimal number

%b

Jan, Feb, ..., Dec (en_US)

Month as locale's abbreviated name

%B

January, February, ..., December (en_US)

Month as locale's full name

%m

01, 02, ..., 12

Month as a zero-padded decimal number

%y

00, 01, ..., 99

Year without century as a zero-padded decimal number

%Y

0001, 0002, ..., 2013, 2014, ..., 9998, 9999

Year with century as a decimal number

%H

00, 01, ..., 23

Hour (24-hour clock) as a zero-padded decimal number

%I

01, 02, ..., 12

Hour (12-hour clock) as a zero-padded decimal number

%p

AM, PM (en_US)

Locale's equivalent of either AM or PM

%M

00, 01, ..., 59

Minute as a zero-padded decimal number

%S

00, 01, ..., 59

Second as a zero-padded decimal number

%f

000000, 000001, ..., 999999

Microsecond as a decimal number, zero-padded on the left

%z

(empty), +0000, -0400, +1030

UTC offset in the form +HHMM or -HHMM (empty string if the object is naive)

%Z

(empty), UTC, EST, CST

Time zone name (empty string if the object is naive)

%j

001, 002, ..., 366

Day of the year as a zero-padded decimal number

%U

00, 01, ..., 53

Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0

%W

00, 01, ..., 53

Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0

%c

Tue Aug 16 21:30:00 1988 (en_US)

Locale's appropriate date and time representation

%x

08/16/1988 (en_US); 16.08.1988 (de_DE)

Locale's appropriate date representation

%X

21:30:00

Locale's appropriate time representation

%%

%

A literal % character

%G

0001, 0002, ..., 2013, 2014, ..., 9998, 9999

ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V)

%u

1, 2, ..., 7

ISO 8601 weekday as a decimal number where 1 is Monday

%V

01, 02, ..., 53

ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4

11.4.3. Leading Zero

  • %#H - remove leading zero (Windows)

  • %-H - remove leading zero (macOS, Linux, *nix)

  • %_H - replace leading zero with space (macOS, Linux, *nix)

  • Works only with formatting

  • raises ValueError while parsing [1]

On Linux and *nix systems:

>>> from datetime import datetime
>>>
>>>
>>> dt = datetime(1961, 4, 12, 6, 7)
>>>
>>> format(dt, '%H:%M')
'06:07'
>>>
>>> format(dt, '%-H:%M')
'6:07'
>>>
>>> format(dt, '%_H:%M')
' 6:07'
>>>
>>> format(dt, '%#H:%M')  
'06:07'

On macOS:

>>> from datetime import datetime
>>>
>>>
>>> dt = datetime(1961, 4, 12, 6, 7)
>>>
>>> format(dt, '%H:%M')
'06:07'
>>>
>>> format(dt, '%-H:%M')
'6:07'
>>>
>>> format(dt, '%#H:%M')  
'#H:07'

On Windows 10:

>>> from datetime import datetime
>>>
>>>
>>> dt = datetime(1961, 4, 12, 6, 7)
>>>
>>> format(dt, '%H:%M')
'06:07'
>>>
>>> format(dt, '%-H:%M')  
Traceback (most recent call last):
ValueError: Invalid format string
>>>
>>> format(dt, '%_H:%M')  
Traceback (most recent call last):
ValueError: Invalid format string
>>>
>>> format(dt, '%#H:%M')  
'6:07'
Table 11.3. Leading Zero

Meaning

With

Without (macOS, Linux)

Without (Windows)

day

%d

%-d

%#d

hour 24h

%H

%-H

%#H

hour 12h

%I

%-I

%#I

day of a year

%j

%-j

%#j

month

%m

%-m

%#m

minute

%M

%-M

%#M

second

%S

%-S

%#S

week number (Sunday first)

%U

%-U

%#U

week number (Monday first)

%W

%-W

%#W

weekday (Sunday first)

%w

%-w

%#w

year short

%y

%-y

%#y

year long

%Y

%-Y

%#Y

11.4.4. String Format Time

  • datetime.strftime()

>>> from datetime import datetime
>>>
>>>
>>> gagarin = datetime(1961, 4, 12, 6, 7)
>>> formatted = gagarin.strftime('%Y-%m-%d %H:%M')
>>>
>>> print(f'Gagarin launched on {formatted}')
Gagarin launched on 1961-04-12 06:07

11.4.5. Format String

>>> from datetime import datetime
>>>
>>>
>>> gagarin = datetime(1961, 4, 12, 6, 7)
>>>
>>> print(f'Gagarin launched on {gagarin:%Y-%m-%d}')
Gagarin launched on 1961-04-12
>>>
>>> print(f'Gagarin launched on {gagarin:%Y-%m-%d %H:%M}')
Gagarin launched on 1961-04-12 06:07
>>> from datetime import datetime
>>>
>>>
>>> gagarin = datetime(1961, 4, 12, 6, 7)
>>> format = '%Y-%m-%d %H:%M'
>>>
>>> print(f'Gagarin launched on {gagarin:{format}}')
Gagarin launched on 1961-04-12 06:07

11.4.6. References

11.4.7. Assignments

Code 11.29. Solution
"""
* Assignment: Datetime Format US
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min

English:
    1. Define `result: str` with `DATA` in long US format
    2. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result: str` z `DATA` w długim formacie amerykańskim
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, must be a str'

    >>> result
    'July 21, 1969 02:56:15 AM'
"""

from datetime import datetime


DATA = datetime(1969, 7, 21, 2, 56, 15)

# DATA in long US format: 'July 21, 1969 02:56:15 AM'
# type: str
result = ...

Code 11.30. Solution
"""
* Assignment: Datetime Format LeadingZero
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min

English:
    1. Define `result: str` with `DATA` in short US format
    2. Make sure, that month, day and hour are without leading zero
    3. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result: str` z `DATA` w krótkim formacie amerykańskim
    2. Upewnij się, że miesiąc, dzień i godzina jest bez wiodącego zera
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * Use `%-I` on \*nix systems (macOS, BSD, Linux)
    * Use `%#I` on Windows

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, must be a str'

    >>> result
    '7/21/69 2:56 AM'
"""

from datetime import datetime


DATA = datetime(1969, 7, 21, 2, 56, 15)

# DATA in short US format: '7/21/69 2:56 AM'
# type: str
result = ...