alex_halford
alex_halford

Reputation: 439

Is there a more concise way of getting today's date, at a specified time in python

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

Answers (2)

Mad Physicist
Mad Physicist

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

Sam
Sam

Reputation: 533

Try the below:

foo = dt.datetime.combine(dt.date.today(), dt.time(3))

Upvotes: 1

Related Questions