Reputation: 22499
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
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
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
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