Remove time in date format in Python

I using:

s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')

I need convert a number in date format (2020-01-13) but when I print final:

2020-01-13 00:00:00

Tried datetime.date(s, '%Y%m%d') but It's returns a error:

an integer is required (got type str)

Is there any command to get only date without hour?

Upvotes: 1

Views: 24803

Answers (4)

Alexander
Alexander

Reputation: 109528

Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.

s = "20200113"
year = int(s[:4])  # 2020
month = int(s[4:6])  # 1
day = int(s[6:8])  # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'

You can also convert directly via strings.

>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'

Upvotes: 1

Phoenixo
Phoenixo

Reputation: 2113

You can use strftime to convert back in the format you need :

import datetime
s = "20200113"

temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00

final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13

Upvotes: 1

oliversm
oliversm

Reputation: 1967

Once you have a datetime object just use strftime

import datetime
d = datetime.datetime.now()  # Some datetime object.
print(d.strftime('%Y-%m-%d'))

which gives

2020-02-20

Upvotes: 2

Tal
Tal

Reputation: 568

You can use .date() on datetime objects to 'remove' the time.

my_time_str = str(final.date())

will give you the wanted result

Upvotes: 2

Related Questions