strptime() not displayiong required format

51 Views Asked by At

I have a variable datetime1="12/31/2016 02:00:00 PM"

However, when i run:

formatted_date = datetime.strptime(datetime1, "%m/%d/%Y %I:%M:%S %p")
print(formatted_date) 

,it displays the result with dashes (-) instead of slashes (/). I want the output as a datestring object such as: 12/31/2016 02:00:00 PM instead of 2016-12-31 00:00:00

datetime1= '12/31/2016 02:00:00 PM'
formatted_date = datetime.strptime(datetime1, "%m/%d/%Y %I:%M:%S %p")
print(formatted_date) 

is giving me: 2016-12-31 02:00:00

instead of 12/31/2016 02:00:00 PM

1

There are 1 best solutions below

0
jsbueno On

"strPtime" is for parse: it takes your date as a string, in the given format, and creates an internal datetime object.

That datetime object, in turn is convertible back to a string with the converse method ".strftime" - F for "format" - which then you can tweak as you want

In this case, if you just want to print the string representing your datetime as it is, just print it at once with print(datetime1), no need to run it through datetime.

Otherwise you want this:

datetime1= '12/31/2016 02:00:00 PM'
date_obj = datetime.strptime(datetime1, "%m/%d/%Y %I:%M:%S %p")
formatted_date = date_obj.strftime("%m/%d/%Y %I:%M:%S %p")
print(formatted_date)

And the intermediate date_obj is a datetime instance, which can do a lot of smart things date-related:

In [7]: date_obj.year
Out[7]: 2016

In [8]: date_obj.isoformat()
Out[8]: '2016-12-31T14:00:00'

In [9]: from datetime import timedelta

In [10]: date_obj + timedelta(days=7 * 365)
Out[10]: datetime.datetime(2023, 12, 30, 14, 0)