Python Format datetime

July 2, 2019

Convert datetime to string

import datetime

now = datetime.datetime.now()
now_str = str(now))
2019-07-02 20:00:27.230410

Format yyyy-MM-dd HH:mm:ss

now_str = now.strftime('%Y-%m-%d %H:%M:%S')
'2019-07-02 20:00:27'

NOTE: Refer strftime format directives.

Format ISO

now_str = now.isoformat()
2019-07-02T20:00:27.230410

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.