1

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 2 Like I said, it was a bonehead thing I just missed along the way. Thanks.
Please mark this as the correct answer to give credit to @kindall! :)
Or mark mine as correct because I actually fixed the code - and answered first.
"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.
6

The best way to do this is with strptime!

print( strptime( ..., "%Y%m%d" ) )

1 Comment

Oh lookie there. This could be useful. TY
2
processdate = "20100818" 
print(processdate[0:4]) # year
print(processdate[4:6]) # month
print(processdate[6:8]) # date 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.