2

i have a bunch of strings like this: s = 3851102123

objective would be to extract the date from it in example:
85 is year
11 is month
02 is day

basically string indexes 1,2 = year, 3,4 = month, 5,6 = day
rest can be discarded, this is what i came up with:

>> x = datetime.strptime("3851102123", ??)

How would one extract the proper indexes?

Should i use regular expressions inside the parentheses to get the date out and then reformat the string ?

Output should like this:

>> 02.11.1985 

1 Answer 1

1

I am not sure if you can do it like that, as strptime will expect a format string and the format string does not allow for variable fields (as you'll need if you want the format to ignore the first number of the string)

You could do something like this: datetime.strptime(the_string[1:7], "%y%m%d").strftime("%d.%m.%Y")

but maybe substrings or regular expressions would be faster.

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

4 Comments

although, how would one check if the string inside the datetime is in the correct format ? For example that the month is not "31" and is indeed between 1-12.Found another batch of strings wrongly formated and they break the code :(
I don't know exactly what would happen if the string is unparseable, I believe a ValueError may be thrown. It will not just pass along as the datetime object have defined ranges of valid values. Can you give an example of the wrongly formatted strings? Check here for details: docs.python.org/library/datetime.html
datetime.strptime("3057102123"[1:7], "%y%m%d") outputs ValueError: unconverted data remains since the month is "71",
go it fixed using exception handling,code: try: (code), except ValueError

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.