Reputation: 439
I need a datetime object whose date is today's date, but whose time is specified (3 am).
I tried this:
dt.now().date() + timedelta(hours=3)
-> Can't add timedelta to dt.date object
foo = dt.now()
foo.hour = 3
foo.minute = 0
foo.second = 0
-> Not writable
This works, but seems ugly:
foo = dt(dt.now().year, dt.now().month, dt.now().day, 3,0,0,0)
Or, alternatively:
foo = dt(dt.now().year, dt.now().month, dt.now().day) + timedelta(hours=3)
Is there a cleaner, more pythonic way of doing this? It feels like 'today at a specific time' should be a fairly common use case...
Upvotes: 0
Views: 93
Reputation: 114230
Just like datetime.datetime
has a classmethod now
, datetime.date
has a method today
(which is different form datetime.datetime.today
).
You can use this method along with datetime.datetime.combine
for a reasonably clean solution:
_3am = time(3, 0, 0)
dt = datetime.combine(date.today(), _3am)
Upvotes: 2