2

I have a string:

dat="012915"

I want to convert it to a date:

01-29-2015

I tried:

import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%Y').date()
dat

but failed:

ValueError: time data '01-29-15' does not match format '%m%d%Y'
William
  • 3,724
  • 9
  • 43
  • 76

5 Answers5

3

%Y is for full year
%y is the short version for year

Your code is totally fine, just change the year directive to lowercase %y will do.

import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
dat
hs-
  • 176
  • 2
  • 5
  • 21
2

I think you are looking for

import datetime
from datetime import datetime
dat="012915"
#lower %y
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)

this will give you

2015-01-29
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
2

Trying this out; changing the format string to '%m%d%y' seems to work. Looking at the python docs:

%y Year without century as a zero-padded decimal number.

%Y Year with century as a decimal number.

So the first one is what you need. Source: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Rain
  • 81
  • 4
0
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)

Change %Y to %y. If you want to use %Y, change dat to '01292015'. y% is formatted as 15 while %Y is formatted as 2015.

CoderCookie10
  • 81
  • 1
  • 10
0
from datetime import datetime
date_str = '012915'
date_obj = datetime.strptime(date_str, '%m/%d/%y')

print("The type of the date is now",  type(date_obj))
print("The date is", date_obj)
Francisco Puga
  • 23,869
  • 5
  • 48
  • 64
Udit Jain
  • 1
  • 1