tags:

views:

72

answers:

3

Wanted an easy way to extract year month and day from a string. Using Python 3.1.2

Tried this:

processdate = "20100818"
print(processdate[0:4])
print(processdate[4:2])
print(processdate[6:2])

Results in:

...2010
...
...

Reread all the string docs, did some searching, can't figure out why it'd be doing this. I'm sure this is a no brainer that I'm missing somehow, I've just banged my head on this enough today.

+2  A: 
processdate = "20100818" 
print(processdate[0:4]) # year
print(processdate[4:6]) # month
print(processdate[6:8]) # date 
duffymo
+6  A: 

With a slice of [4:2], you're telling Python to start at character index 4 and stop at character index 2. Since 4 > 2, you are already past where you should stop when you start, so the slice is empty.

Did you want the fourth and fifth characters? Then you want [4:6] instead.

kindall
Ah somewhere along the way I got the impression that 4:2 was start char 4 length of 2 not start char 4 to char 2Like I said, it was a bonehead thing I just missed along the way.Thanks.
Alan
Please mark this as the correct answer to give credit to @kindall! :)
jathanism
Or mark mine as correct because I actually fixed the code - and answered first.
duffymo
I'll give you an upvote at least, duffy!
kindall
"answered first" is never a reason to mark one item a solution over another; the person who answered second probably put more thought into the answer.
Glenn Maynard
+5  A: 

The best way to do this is with strptime!

print( strptime( ..., "%Y%m%d" ) )
katrielalex
Oh lookie there. This could be useful. TY
Alan