If I have a datetime object such as datetime.datetime(2017, 7, 20, 15, 0)
, how do I convert it back to a string in the format of "2017-07-20-15-00"
?
Asked
Active
Viewed 5,443 times
1

hiro protagonist
- 44,693
- 14
- 86
- 111

Mat.S
- 1,814
- 7
- 24
- 36
-
3Possible duplicate of [How do I turn a python datetime into a string, with readable format date?](https://stackoverflow.com/questions/2158347/how-do-i-turn-a-python-datetime-into-a-string-with-readable-format-date) – Nodir Rashidov Jul 22 '17 at 07:33
-
https://stackoverflow.com/a/2158454/6468413 – Nodir Rashidov Jul 22 '17 at 07:34
1 Answers
2
python has date formattting built-in either using datetime.strftime
, str.format
or the new f-strings in python >= 3.6:
from datetime import datetime
dt = datetime(2017, 7, 20, 15, 0)
# str.format
strg = '{:%Y-%m-%d %H-%M-%S}'.format(dt)
print(strg) # 2017-07-20 15-00-00
# datetime.strftime
strg = dt.strftime('%Y-%m-%d %H-%M-%S')
print(strg) # 2017-07-20 15-00-00
# f-strings in python >= 3.6
strg = f'{dt:%Y-%m-%d %H-%M-%S}'
print(strg) # 2017-07-20 15-00-00
you can tweak the format string according to your needs. strftime()
and strptime()
Behavior explains what the format specifiers mean.

hiro protagonist
- 44,693
- 14
- 86
- 111