4

For example, I have the int 043017, which I want converted to 04/30/17 (April 30, 2017), I want to be able to convert any int of that format into datetime, how can this be accomplished?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Alex
  • 486
  • 1
  • 7
  • 19

1 Answers1

6
import datetime
d = datetime.datetime.strptime(input, '%m%d%y')
mohammad
  • 2,232
  • 1
  • 18
  • 38
  • 2
    This is the way to do it, although it requires a string as input. An integer will not work. @Alex you should convert the integer to a string, and then use this method. Note that you cannot keep the leading 0 in a python integer. (You could check the string length and a pad as necessary) – Deem Apr 30 '17 at 18:59
  • it does not work with a string '043017', i tried %x also – Alex Apr 30 '17 at 19:11
  • @Alex It's working fine for me with this string. You cant print d to see it. Do you get any error? – mohammad Apr 30 '17 at 19:13
  • ValueError: time data '043117' does not match format '%m%d%Y' this is all it says. i dont know why – Alex Apr 30 '17 at 19:17
  • 1
    `%Y` is a four-digit year, so of course it doesn't match. `%y` is the format for a 2-digit year – jasonharper Apr 30 '17 at 19:20
  • @Alex You should use lowercase 'y'. – mohammad Apr 30 '17 at 19:24
  • now that i got that, how can I convert '043017' to a string '04/30/17' – Alex Apr 30 '17 at 19:51
  • '/'.join([a[:2], a[2:4], a[4:]]) where a is your string – mohammad Apr 30 '17 at 19:57