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"?
-
3Possible duplicate of How do I turn a python datetime into a string, with readable format date?Nodir Rashidov– Nodir Rashidov2017-07-22 07:33:57 +00:00Commented Jul 22, 2017 at 7:33
-
stackoverflow.com/a/2158454/6468413Nodir Rashidov– Nodir Rashidov2017-07-22 07:34:02 +00:00Commented Jul 22, 2017 at 7:34
Add a comment
|
1 Answer
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.