Aufwind
Aufwind

Reputation: 26258

How to parse a date and only the date from a `date_string` in python?

I have a variable containing a string from which I want to parse the date. I tryed this:

import datetime
date_string = "July 2010"
parsed_date = datetime.datetime.strptime(date_string, "%B %Y")
print parsed_date
# datetime.datetime(2010, 7, 1, 0, 0))

I assume the 1 is added by datetime, because a date must have a day? But why are there two zeroes? I assume this shall be the time? Is there a way to avoid the time? I only want the date.

Upvotes: 0

Views: 2776

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318508

Simply call .date() on the datetime object. This returns a date object.

In [5]: dt
Out[5]: datetime.datetime(2010, 7, 1, 0, 0)
In [6]: dt.date()
Out[6]: datetime.date(2010, 7, 1)

For your other subquestions:

  • Yes, the 0, 0 is the time.
  • A date always has year, month and day (with 1 <= day <= 31).

Upvotes: 4

Related Questions