0

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...

alex_halford
  • 369
  • 3
  • 10

2 Answers2

2

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)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
1

Try the below:

foo = dt.datetime.combine(dt.date.today(), dt.time(3))
Sam
  • 533
  • 3
  • 12