gadss
gadss

Reputation: 22499

how to print only date and not include the time in datetime.datetime.strptime()

I have this code :

>>> import datetime
>>> l = '2011-12-02'
>>> t = datetime.datetime.strptime(l, '%Y-%m-%d')
>>> print t
2011-12-02 00:00:00

my question is, it is possible that only the 2011-12-02 will be printed?

Upvotes: 26

Views: 55562

Answers (5)

Faizan Khalid Mohsin
Faizan Khalid Mohsin

Reputation: 307

The simplest and easiest way is to use the method function .date()

l = '2011-12-02'
t = datetime.datetime.strptime(l, '%Y-%m-%d')

print(t.date())

You get:

2011-12-02

More generally:

If you have some datetime like this datetime.datetime.now() you can simply add .date() at the end:

print(datetime.datetime.now().date())

Which gives:

2023-07-04

This is what I personally prefer over the solutions of strftime('%Y-%m-%d') and print '{:%Y-%m-%d}'.format(d) which also indeed work perfectly well.

Upvotes: 2

Blender
Blender

Reputation: 298354

With strftime():

print t.strftime('%Y-%m-%d')

Upvotes: 9

Alpha01
Alpha01

Reputation: 856

You have to specify the output format for the date, e.g. by using

print t.strftime("%Y-%m-%d")

All the letter after a "%" represent a format: %d is the day number, %m is the month number, %y is the year last two digits, %Y is the all year

Upvotes: 2

Dan D.
Dan D.

Reputation: 74655

>>> t.strftime('%Y-%m-%d')
'2011-12-02'

Upvotes: 38

hungneox
hungneox

Reputation: 9829

I think you should use like this

 d = datetime.datetime(2011,7,4)
 print '{:%Y-%m-%d}'.format(d)

or your code:

import datetime
l = '2011-12-02'
t = datetime.datetime.strptime(l, '%Y-%m-%d')
print '{:%Y-%m-%d}'.format(t)

Upvotes: 1

Related Questions