1

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"?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.