I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same)
end_date = lastItem.pub_date
currently the end date is 2002-01-11 12:34:56
What do I need to do to get this to change it to 00:00:00?
i tried:
end_date.hour = '00'
but got: 'datetime.datetime' object attribute 'time' is read-only
Using datetimes's "combine" with the time.min and time.max will give both of your datetimes.
For example:
from datetime import date, datetime, time
pub_date = date.today()
min_pub_date_time = datetime.combine(pub_date, time.min)
max_pub_date_time = datetime.combine(pub_date, time.max)
Result with pub_date of 6/5/2013:
min_pub_date_time -> datetime.datetime(2013, 6, 5, 0, 0)
max_pub_date_time -> datetime.datetime(2013, 6, 5, 23, 59, 59, 999999)
Try this:
import datetime
pub = lastItem.pub_date
end_date = datetime.datetime(pub.year, pub.month, pub.day)
Are you sure you don't want to use dates instead of datetimes? If you're always setting the time to midnight, you should consider using a date. If you really want to use datetimes, here's a function to get the same day at midnight:
def set_to_midnight(dt):
midnight = datetime.time(0)
return datetime.datetime.combine(dt.date(), midnight)
For tz-aware dates it should be:
datetime.combine(dt.date(), datetime.min.time(), dt.tzinfo)
datetime instance attributes like year, month, day, hour, etc are read-only, so you just have to create a new datetime object and assign it to end_date.
Related
I have python date object like
datetime.date(2020, 3, 29) # d1, django DateField in database
Now i want to get UTC timestamp of that date object d1 at midnight
I searched a lot but nothing works.
I tried
d2 = datetime.combine(d1, datetime.min.time())
d2.timestamp() // This is localtimezone i want in UTC
Not sure why i need to add time
assuming your date object d is in UTC, you could simply add midnight time (00:00:00) and timezone info UTC and then apply timestamp() method to get the desired timestamp. Example:
import datetime as dt
d = dt.date(2020, 3, 29)
ts_utc = dt.datetime.combine(d, dt.time(0,0,0), tzinfo=dt.timezone.utc).timestamp()
print(ts_utc)
# 1585440000.0
check = dt.datetime.utcfromtimestamp(ts_utc)
print(check)
# 2020-03-29 00:00:00
Note: it is important to set the timezone, otherwise, the timestamp() method assumes that the input is in the timezone that the machine you run this code on is set to!
How can I create a date time object for 9:00 AM UTC to use for comparison with the current utc time?
new_date = datetime.datetime(2019, 12, 2, 10, 24, 34, 198130)
I want to do it without the year, minutes and seconds.
If you don't need the date part of it, use datetime.time:
import datetime
nine_am = datetime.time(9)
if datetime.datetime.utcnow().time() > nine_am:
...
I need to determine a date given the seconds elapsed since said date.
I have the date in the format of YYYY-MM-DD hh:mm:ss and I am aware that it can be converted to a datetime.datetime() object as a good starting point but how can I use a date time object as a reference point and accurately derive the date by extrapolating a given number of seconds?
You can use the method timedelta of the datetime module like this:
import datetime
start_date = datetime.datetime(2017, 10, 19, 15, 0, 0)
new_date = start_date + datetime.timedelta(seconds=5*86400)
## adds 5 days = 5*86400 seconds
print(new_date)
Give the output
2017-10-24 15:00:00
I need to construct datetime object from different parameters. For example, I get these parameters:
integer number from 0 to 6. This one indicates weekday.
hour and minutes in float format (from 0.0 to 24.0).
And then I know which week of the current year it is going to be. So, for example, let say that datetime should be from 2014-07-18 00:00:00 to 2014-07-24 23:59:00 (seconds can be ignored and left at 00). So to get exact datetime I need to use above defined parameters.
Let say I would get these parameters 4 (meaning Friday), and 9.5 (meaning 09:30).
So by doing such construction, I should get a date that would be: 2014-07-22 09:30:00. How could accomplish such thing?
Do I need to somehow get for example day of the month by knowing which is the week of the year and which weekday it is?
P.S. A bit more detailed example of what I'm trying to accomplish
from datetime import datetime
today = datetime.today() #using this to get the week I'll be working with.
today = today.replace(day=?) #how to get which day I
#need to enter by having weekday and knowing that week is the present one?
You could do something like that, if your parameters are weekday and t (time):
from datetime import timedelta
monday = today - timedelta(days=today.weekday())
result = (monday + timedelta(days=weekday)).replace(hour=int(t), minutes=int((t - int(t)) * 60))
If you have a starting date, use the relative value of the datetime.datetime.weekday() value to construct a timedelta() object that'll put you onto the right weekday, then replace the hour and minutes:
from datetime import timedelta
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday() - weekday
return (reference - timedelta(days=days)).replace(
hour=int(hour), minute=int(minute), second=0, microsecond=0)
Demo:
>>> from datetime import timedelta, datetime
>>> def relative_date(reference, weekday, timevalue):
... hour, minute = divmod(timevalue, 1)
... minute *= 60
... days = reference.weekday() - weekday
... return (reference - timedelta(days=days)).replace(
... hour=int(hour), minute=int(minute), second=0, microsecond=0)
...
>>> relative_date(datetime.now(), 4, 9.5)
datetime.datetime(2014, 8, 22, 9, 30)
>>> relative_date(datetime.now() - timedelta(days=30), 6, 11.75)
datetime.datetime(2014, 7, 27, 11, 45)
I would use timedelta to add the difference between weekdays to the datetime
from datetime import datetime, timedelta
friday = 4
today = datetime.now()
friday_this_week = today + timedelta(friday - today.weekday())
In your case just replace today with a date that is in the week you want.
I need to get date objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().year, 12, 31)
The only real improvement that comes to mind is to give your variables more descriptive names than a and b.
from datetime import datetime
starting_day_of_current_year = datetime.now().date().replace(month=1, day=1)
ending_day_of_current_year = datetime.now().date().replace(month=12, day=31)
There is nothing in the python library but there are external libraries that wrap this functionality up. For example, pandas has a timeseries library, with which you can do:
from datetime import date
from pandas.tseries import offsets
a = date.today() - offsets.YearBegin()
b = date.today() + offsets.YearEnd()
Whilst pandas is overkill if all you want is year begin and year end functionality, it also has support for a lot of other high level concepts such as business days, holiday calendars, month/quarter/year offsets: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects
You'll have some funky stuff going on if you happen to be running this late on New Year's Eve and the two calls to today() cross the year boundary. It's safer to do this:
from datetime import date
epoch_year = date.today().year
year_start = date(epoch_year, 1, 1)
year_end = date(epoch_year, 12, 31)
import datetime
year = 2016
first_day_of_year = datetime.date.min.replace(year = year)
last_day_of_year = datetime.date.max.replace(year = year)
print(first_day_of_year, last_day_of_year)
duh.
What if we want to get the exact time the year begins or ends? Same thing. Replace datetime.date with datetime.datetime, and there you go, you got the first last day of year in datetime.datetime format.
To make this even fancier, wrap the whole thing in a function:
import datetime
def year_range(year, datetime_o = datetime.date):
return (
datetime_o.min.replace(year = year),
datetime_o.max.replace(year = year)
)
print(year_range(2016, datetime.date))
print(year_range(2016, datetime.datetime))
Output:
(datetime.date(2016, 1, 1), datetime.date(2016, 12, 31))
(datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 12, 31, 23, 59, 59, 999999))
use relative timedelta and substract from date object
from dateutil.relativedelta import relativedelta
import datetime
date = datetime.date.today()
fistOfYear = date - relativedelta(years=0, month=1, day=1)
one genius way to find out first and last day of year is code below
this code works well even for leap years
first_day=datetime.date(year=i,month=1, day=1)
first_day_of_next_year=first_day.replace(year=first_day.year+1,month=1, day=1)
last_day=first_day_of_next_year-jdatetime.timedelta(days=1)