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.
source to share
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
source to share
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(...)
)
source to share
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.
source to share