Python - datetime Formatting

Formatting datetime in Python can be a 'pain'.


Formatting works in two directions
- From a string to datetime.
- From a datetime to string.

The easiest way to remember how things work using the strptime and strftime is that:
strptime (string)(parse)(time)
strftime (string)(format)(time)

Format a datetime to a string

from datetime import datetime

print(datetime.today().strftime('%Y-%m-%d %H:%M:%S'))

2020-07-22 10:07:16



Parse a String to datetime

from datetime import datetime

date_time = '2020-07-22 10:07:16'
dt_object = datetime.strptime(date_time, '
%Y-%m-%d %H:%M:%S')

Comments

Popular posts from this blog

Recursively Delete files of the Same Name in S3

ORACLE RDS granting select privileges to users.