user2001872
user2001872

Reputation: 25

Python: trouble converting string into date

I am somewhat new to Python and have a seemingly simple question.

I have a python script that interacts with an API (RHN Satellite if you're curious). This API returns a date in the form of a string and it always trims leading 0's. For example, 6/1/13 or 10/9/12. I need to convert this string to a date and determine the day of the year it is.

Here is what I know:

today = datetime.datetime.now()
print today.strftime('%j')

...will return today's day of year (175). This works fine for a datetime object but I am having trouble converting the string given by the API to an actual date. If I use:

date = datetime.datetime.strptime(var, '%m/%d/$y')

I get error:

ValueError: time data '5/2/13' does not match format '%m/%d/$y'

I'm guessing because it's expecting leading 0's ? How do I get around this?

In the end, I am trying to subtract the variable date given from the current date but I can't do that until I convert the string.

Thanks for the help!

Upvotes: 2

Views: 168

Answers (3)

Jon Clements
Jon Clements

Reputation: 142126

Correct the $y to %y and I'd use format instead of strftime:

from datetime import datetime
print format(datetime.strptime('5/2/13', '%m/%d/%y'), '%j')

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61512

I think you just have a typo, use %y instead of $y:

date = datetime.datetime.strptime(var, '%m/%d/%y')

Upvotes: 2

Nick Peterson
Nick Peterson

Reputation: 771

This code works for me, provided you change $y to %y in the format code.

Upvotes: 2

Related Questions