Strptime date time in python

I've tried the following code:

import datetime
d = datetime.datetime.strptime("01/27/2012", "%m/%d/%Y")
print(d)

      

and the output is:

2012-01-27 00:00:00

      

I am using Linux Mint:

test@testsrv ~/pythonvault $ date
Fri Jun 16 21:40:57 EEST 2017

      

So the question is, why does the python code output return date in "%Y/%m/%d" ( 2012-01-27 )

instead of format "%m/%d/%Y"

?

Please note that I am using python 2.7

Any help would be appreciated.

+8


source to share


5 answers


You need to make sure you enter the correct input

datetime.strptime(date_string,date_string_format).strftime(convert_to_date_string_format)

      

To print the date in the specified format, you need to provide the format as shown below.

import datetime
d =datetime.datetime.strptime("01/27/2012","%m/%d/%Y").strftime('%m/%d/%Y')
print d

      



Output:

01/27/2012

      

→ Demo <<

+14


source


Function

datetime.strptime(date_string, format)

returns an object datetime

matching date_string

parsed as per format

. When you print the object datetime

, it is formatted as an ISO 8601 string,YYYY-MM-DDTHH:MM:SS

Literature:



+3


source


As clearly noted in the comments, you are parsing a datetime object using the format you specified.

strptime(...)

Str ing P ass Time . You have specified a format for interpreting a string to initialize a Datetime object, but this format is only used for initialization. By default, when you send this datetime object, you get a view str(DatetimeObjectInstance)

(in your case str(d)

).

If you need a different format you should use Str ing F ormat Time ( strftime(...)

)

+1


source


import datetime

str_time= "2018-06-03 08:00:00"
date_date = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print date_date

      

0


source


There is a difference between datetime.strp[arse]time()

and datetime.strf[ormat]time()

.

The first one strptime()

allows you to create a date object from a string source, provided that you can tell it what format to expect:

strDate = "11-Apr-2019_09:15:42"
dateObj = datetime.strptime(strDate, "%d-%b-%Y_%H:%M%S")

print(dateObj)  # shows: 2019-04-11 09:15:42

      

The second, strftime()

allows you to export your date object to a string in the format of your choice:

dateObj = datetime(2019, 4, 11, 9, 19, 25)
strDate = dateObj.strftime("%m/%d/%y %H:%M:%S")

print(strDate)  # shows: 04/11/19 09:19:25

      

What you see is just the default string format for the datetime object because you didn't explicitly tell it which format to use.

Check http://strftime.org/ for a list of all the different string format options that are available.

0


source







All Articles