2

I want to convert a string to a date format using Python datetime.strptime.

However, I set the format to '%m/%d/%y' but the result is '%Y-%m-%d%H:%M:%S'. What's the reason?

convert.py

date_str = ['11/10/2021', '12/15/2021', '2/26/2022', '3/10/2021', '3/10/2021', '3/11/2021']
replace_format = datetime.strptime(date_str, '%m/%d/%Y')

result

print(replace_format)
2022-03-14 00:00:00
2022-04-13 00:00:00
2022-05-11 00:00:00
2022-06-16 00:00:00
2022-06-18 00:00:00
2022-06-18 00:00:00
7
  • The default format of datetime, when you call print on it is used, which is '%Y-%m-%d %H:%M:%S'. You can use replace_format.strftime('%m/%d/%y') to achieve the desired format. Commented Jun 21, 2022 at 14:58
  • 1
    strptime parses a string to a datetime object. The datetime object's default representation (as a string) happens to be %Y-%m-%d %H:%M:%S. But that's just a matter how it is displayed to you when you print it. Commented Jun 21, 2022 at 15:02
  • @DB not using pandas Commented Jun 21, 2022 at 15:04
  • @hoboman Thanks! Actually, the result I want is '%Y-%m-%d%H:%M:%S'. Is there any problem if I keep setting this format to '%m/%d/%Y'? Commented Jun 21, 2022 at 15:10
  • 1
    @JIN This is just a representation of the underlying object. strftime does not change anything in the object, it is just a string representation of it. Commented Jun 21, 2022 at 15:45

2 Answers 2

4

Call date():

from datetime import datetime

date_str = ['11/10/2021', '12/15/2021', '2/26/2022', '3/10/2021', '3/10/2021', '3/11/2021']
for d in date_str:
    replace_format = datetime.strptime(d, '%m/%d/%Y').date()
    print(replace_format)

Result:

2021-11-10
2021-12-15
2022-02-26
2021-03-10
2021-03-10
2021-03-11

Note: Your code did not compile for me in Python 3.7 so I put each item from the date list in a loop.

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

3 Comments

I set the format to '/', but why the output is '-' ?
you can use string replace or just remove the slashes stackoverflow.com/q/29295402/4225229
your answer is misleading, could have used strftime('%m/%d/%Y') instead of date(), but we don't even know what OP wants to achieve
0

You didn't set the format by using strptime(), you are parsing it, i.e. converting string to datetime object.

datetime/date objects will always output YYYY-MM-DD without additional formatting

To output string from object with specific format, use strftime('%m/%d/%Y')

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.