Reputation: 8025
I am trying to get the date to be yesterday at 11.30 PM.
Here is my code:
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
PERIOD=yesterday.strftime ('%Y-%m-%d')
new_period=PERIOD.replace(hour=23, minute=30)
print new_period
however i am getting this error:
TypeError: replace() takes no keyword arguments
any help would be appreciated.
Upvotes: 49
Views: 127463
Reputation: 80
In one line, here you go
import datetime
new_period=(datetime.datetime.today()- datetime.timedelta (days=1)).replace(hour=23, minute=30)
Upvotes: 0
Reputation: 350
You can use datetime.combine(date, time, tzinfo=self.tzinfo)
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
t = datetime.time(hour=23, minute=30)
print(datetime.datetime.combine(yesterday, t))
Upvotes: 21
Reputation: 552
Is this what you want?
from datetime import datetime
yesterday = datetime(2014, 5, 12, 23, 30)
print yesterday
Edited
from datetime import datetime
import calendar
diff = 60 * 60 * 24
yesterday = datetime(*datetime.fromtimestamp(calendar.timegm(datetime.today().utctimetuple()) - diff).utctimetuple()[:3], hour=23, minute=30)
print yesterday
Upvotes: 5
Reputation: 7472
First, change datetime.date.today()
to datetime.datetime.today()
so that you can manipulate the time of the day.
Then call replace
before turning the time into a string.
So instead of:
PERIOD=yesterday.strftime ('%Y-%m-%d')
new_period=PERIOD.replace(hour=23, minute=30)
Do this:
new_period=yesterday.replace(hour=23, minute=30).strftime('%Y-%m-%d')
print new_period
Also keep in mind that the string you're converting it to displays no information about the hour or minute. If you're interested in that, add %H
for hour and %M
for the minute information to your format string.
Upvotes: 68