Crowno
Crowno

Reputation: 3

removing time from date string

have a few dates in a file (eg. 2021-06-15) wrote a code to convert them from string to datetime format

x = str(line[-1])
            dates = datetime.strptime(x, "%Y-%m-%d")
            print(dates)

but the result is 2021-06-15 00:00:00 how do I remove the time part?

Upvotes: 0

Views: 633

Answers (2)

chitown88
chitown88

Reputation: 28565

add on the .date() method

from datetime import datetime

x = '2021-06-01'

dates = datetime.strptime(x, "%Y-%m-%d").date()
print(dates)

Output with time:

dates = datetime.strptime(x, "%Y-%m-%d")
print(dates)

2021-06-01 00:00:00

Output without time:

dates = datetime.strptime(x, "%Y-%m-%d").date()
print(dates)

2021-06-01

Upvotes: 1

Utpal Kumar
Utpal Kumar

Reputation: 300

If yo want date only, try this

from datetime import datetime

date = datetime.strptime(x, "%Y-%m-%d").date()

Here x is the time you specify

Upvotes: 0

Related Questions