Python Date Utility Library

Is there a library in python that can set dates on a specific day? I would like to use this for data analysis. Often I have a time series of dates, but for aggregation purposes, I would like to be able to quickly create dates associated with this day - for example, the first date of the month, the first day of the week, etc.

I think I could create my own, but if something there would already be good.

thanks

+4
source share
2 answers

See dateutil .

repetition rules and relative deltas are what you want.

For example, if you want to get the last Monday:

 import dateutil.relativedelta as rd import datetime last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1)) 
+6
source

time and datetime modules

For some of your purposes, you can use the time module with strftime() or the date module with strftime() . This allows you to pull, among other things:

  • week number of the year
  • weekday number (you can also use the weekday() method to get the number on weekdays between 0 for Monday and 6 for Sunday),
  • year
  • month,

Which will be enough to calculate the first day of the month, the first day of the week and some other data.

Examples

To pull the necessary data, do the following:

  • to display the day number of the week

     >>> from datetime import datetime >>> datetime.now().weekday() 6 
  • to use the replace() function of the datetime object on the first day of the month:

     >>> 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 suggested by Yu.F. Sebastian in the comments, datetime objects have weekday() methods, which makes using int(given_date.strftime('%w')) pretty pointless. I updated the answer above.

+2
source

Source: https://habr.com/ru/post/1399574/


All Articles