MatLab can take a date and move it to the end of the month, quarter, etc. using the dateshift(...) function.
Is there an equivalent function in Python?
I'm not sure if it counts as the same, but the datetime module can make times available as a timetuple, with separate components for year, month, day etc. This is easy to manipulate directly to advance to the next month, etc.
If you don't mind using an extension, check out dateutil. The list of features starts with:
Computing of relative deltas (next month, next year, next monday, last week of month, etc);
The documentation for dateutil.relativedelta shows how to advance to various points.
I think calendar.monthrange should do it for you, e.g.:
>>> import datetime, calendar
>>> year = int(input("Enter year: "))
Enter year: 2012
>>> month = int(input("Enter month: "))
Enter month: 3
>>> endOfMonthDate = datetime.date(year, month, calendar.monthrange(year, month)[1])
>>> endOfMonthDate
datetime.date(2012, 3, 31)
>>>
You might find other helpful functions here: https://docs.python.org/2/library/calendar.html and here: https://docs.python.org/2/library/datetime.html
Related
In a Django query, how would you filter by a timestamp's week within a month?
There's a built-in week accessor, but that refers to week-of-the-year, e.g. 1-52. As far as I can tell, there's no other built-in option.
The only way I see to do this is to calculate the start and end date range for the week, and then filter on that using the conventional means.
So I'm using a function like:
def week_of_month_date(year, month, week):
"""
Returns the date of the first day in the week of the given date's month,
where Monday is the first day of the week.
e.g. week_of_month_date(year=2022, month=8, week=2) -> date(2022, 8, 7)
"""
assert 1 <= week <= 5
assert 1 <= month <= 12
for i in range(1, 32):
dt = date(year, month, i)
_week = week_of_month(dt)
if _week == week:
return dt
and then to calculate for, say, the 3rd week of July, 2022, I'd do:
start_date = week_of_month_date(2022, 7, 3)
end_date = week_of_month_date(2022, 7, 3) + timedelta(days=7)
qs = MyModel.objects.filter(created__gte=start_date, created__lte=end_date)
Is there an easier or more efficient way to do this with the Django ORM or SQL?
The easiest way to do this using datetime objects is to quite simply subtract the current date weekly year value, with the yearly week value for the 1st day (or 1st week) of the month.
You can use the .isocalendar() function to achieve this:
dt.isocalendar[1] - dt.replace(day=1).isocalendar()[1] + 1
Basically if the week is 46 and that means the first week is week 44 then the resulting output should be 2.
UPDATE
I misunderstood the question, the answer is clear below. However, you may want to consider revising your function based on my above comments.
Come to think of it, if you have a datetime object, you can get the isocalendar week and filter using that like so:
MyModel.objects.filter(created__week=dt.isocalendar()[1])
dt.isocalendar() returns essentially a tuple of 3 integers, [0], is the year, [1], is the iso week (1-52 or 53) and [2], the day of the week (1-7).
As per the docs here:
https://docs.djangoproject.com/en/4.1/ref/models/querysets/#week
There is a built-in filter for isoweek out of the box :)
However, filtering by "week of month" is not possible within the realms of "out of the box".
You might consider writing your own query expression object which accepts an isocalendar object and converts that? But I think you would be better off converting a datetime object and use the isoweek filter.
There's a neat little blog post here to get you started if you really want to do that:
https://dev.to/idrisrampurawala/writing-custom-django-database-functions-4dmb
I have a Deephaven DateTime in the New York (US-East) timezone and I'd like to get the year, month, and day (of the month) numbers from it as integers in Python.
Deephaven's time module has these utilities. You may have used it to create a Deephaven DateTime in the first place.
from deephaven import time as dhtu
timestamp = dhtu.to_datetime("2022-04-01T12:00:00 NY")
The following three methods will give you what you're looking for:
year - Gets the year
month_of_year - Gets the month
day_of_month - Gets the day of the month
All three methods will give you what you want based on the DateTime itself and your preferred time zone.
tz_ny = dhtu.TimeZone.NY
year = dhtu.year(timestamp, tz_ny)
month = dhtu.month_of_year(timestamp, tz_ny)
day = dhtu.day_of_month(timestamp, tz_ny)
So basically what I want to do is to subtract the date of birth from todays date in order to get a persons age, I've successfully done this, but I can only get it to show the persons age in days.
dateofbirth = 19981128
dateofbirth = list(str(dateofbirth))
now = datetime.date.today()
yr = dateofbirth[:4]
yr = ''.join(map(str, yr))
month = dateofbirth[4:6]
month = ''.join(map(str, month))
day = dateofbirth[6:8]
day = ''.join(map(str, day))
birth = datetime.date(int(yr), int(month), int(day))
age = now - birth
print(age)
In this case, age comes out as days, is there any way to get it as xx years xx months and xx days?
You can use strptime:
>>> import datetime
>>> datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.datetime(1998, 11, 28, 0, 0)
>>> datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.timedelta(5823, 81486, 986088)
>>> print (datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d'))
5823 days, 22:38:18.039365
The result of subtracting two dates in Python is a timedelta object, which just represents a duration. It doesn't "remember" when it starts, and so it can't tell you how many months have elapsed.
Consider that the period from 1st January to 1st March is "two months", and the period from 1st March to 28th April is "1 month and 28 days", but in a non-leap year they're both the same duration, 59 days. Actually, daylight savings, but let's not make this any more complicated than it needs to be to make the point ;-)
There may be a third-party library that helps you, but as far as standard Python libraries are concerned, AFAIK you'll have to roll your sleeves up and do it yourself by finding the differences of the day/month/year components of the two dates in turn. Of course, the month and day differences might be negative numbers so you'll have to deal with those cases. Recall how you were taught to do subtraction in school, and be very careful when carrying numbers from the month column to the days column, to use the correct number of days for the relevant month.
I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)
Is there a library in python that can produce date dimensions given a certain day? I'd like to use this for data analysis. Often I have a time series of dates, but for aggregation purposes I'd like to be able to quickly produce dates associated with that day - like first date of month, first day in week, and the like.
I think I could create my own, but if there is something out there already it'd be nice.
Thanks
Have a look at dateutil.
The recurrence rules and relative deltas are what you want.
For example, if you wanted to get last monday:
import dateutil.relativedelta as rd
import datetime
last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1))
time and datetime modules
For some of your purposes you can use time module with strftime() method or date module with its strftime() method. It allows you to pull, among other data:
number of the week of the year,
number of the weekday (you can also use weekday() method for getting weekday number between 0 for Monday and 6 for Sunday),
year,
month,
Which will suffice to calculate first day of the month, first day of the week and some other data.
Examples
To pull the data you need, do just:
to pull the number of the day of the week
>>> from datetime import datetime
>>> datetime.now().weekday()
6
to pull the first day of the month use replace() function of datetime object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 3, 3, 21, 41, 20, 953000)
>>> first_day_of_the_month = datetime.now().replace(day=1)
>>> first_day_of_the_month
datetime.datetime(2012, 3, 1, 21, 41, 20, 953000)
EDIT: As J.F. Sebastian suggested within comments, datetime objects have weekday() methods, which makes using int(given_date.strftime('%w')) rather pointless. I have updated the answer above.