Python Datetime round timedelta to nearest biggest unit - python

I've been making a forum as a learning experience. I have a timestamp for every post, which I convert to a timedelta (how much time ago it was). I want to output the time like so:
If it's < 1 minute display it in seconds
If it's >= 1 minute and < 1 hour display it in minutes
If it's >= 1 hour and < 1 day display it in hours
If it's >= 1 day and < 1 week display it in days
If it's >= 1 week and < 1 month display it in weeks
If it's >= 1 month and < 1 year display it in months
If it's >= 1 year display it in years
What is the best way to do this in python and datetime?

Use a third-party library. For example, readabledelta is a timedelta subclass which prints human-readable.
>>> from readabledelta import readabledelta
>>> from datetime import timedelta
>>> print(readabledelta(timedelta(seconds=1)))
1 second
>>> print(readabledelta(timedelta(seconds=60)))
1 minute
>>> print(readabledelta(timedelta(seconds=60*60)))
1 hour
>>> print(readabledelta(timedelta(seconds=60*60*24)))
1 day
>>> print(readabledelta(timedelta(seconds=60*60*24*7)))
1 week
You can not easily use months or years, because the length of the unit is not well defined (a month could be 28-31 days, and a year could be 365-366 days).

Related

Python elegant way of finding the last weekday [duplicate]

This question already has answers here:
Previous weekday in Python
(4 answers)
Closed 1 year ago.
I need to find the last weekday (without considering holidays). Is there any more elegant/robust way of implementing this than the one I'm currently using?
from datetime import date
b = date.today() - timedelta(days=1)
while b.weekday()>=5:
b = b - timedelta(days=1)
Something like this might work (untested):
from datetime import date, timedelta
b = date.today() - timedelta(days=1)
current_day = b.weekday() # 0 for Monday, 6 for Sunday
# go back 1 day for Sat, 2 days for Sun, 0 for other days
days_to_go_back = max(current_day - 4, 0)
b -= timedelta(days=days_to_go_back)

How to get time humanized time difference without external libraries

I have two times, how can I get the time difference of these 2 aware datetime objects in a human readable format. What I mean by human readable format would be 1 year 3 months 2 weeks 4 days 1 hour 2 minutes and 19 seconds.
However, if the time difference is shorter, it would give a readable format like 2 minutes and 3 seconds (It wouldn't tell us 0 years 0 months 0 weeks 0 days 0 hours 2 minutes and 52 seconds). Or if its just seconds left then it would be 15 seconds
Year is classified as 365.25 days
Month is classified as 30.4375 days

Dates out of order

Why does it starts with december? And 1 1 repeats at the end. Whats the more Pythonic way to iterate over all days in a given year (with handling the leap year)?
import calendar
a = calendar.Calendar(0)
for b in range(1,13):
for x in a.itermonthdates(2016,b):
print x.month, x.day
Output:
12 28
12 29
12 30
12 31
1 1
1 2
1 3
..
..
..
Full Output:
http://pastebin.com/nnP4ADQK
itermonthdates returns complete weeks:
itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.
You could just reject the dates where year is not 2016:
import calendar
a = calendar.Calendar(0)
g = (x for b in xrange(1, 13) for x in a.itermonthdates(2016, b) if x.year == 2016)
print next(g)
Output:
2016-01-01
itermonthdates
returns all weeks which includes days of month. So check should be done for all months.
import calendar
a = calendar.Calendar(0)
for b in range(1,13):
for x in a.itermonthdates(2017,b):
if x.month==b:
print x #x.month, x.day

Week Number for Actual Calendar Python

Can someone tell me how to get a week number in Python for actual calendar.
Ex: 2016-01-01 to 2016-01-07 = week 1
2016-01-08 to 2016-01-14 = week 2
I tried 2 ways but none of them are working
Using isocalendar()
But that does not work for year end and year start week. For ex:
datetime.date(2016,01,01).isocalendar()[1]
# should be: 1
# got 53
is the following:
dt = date(2016,01,02)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 00
dt = date(2016,01,03)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 01
Both the ways do not satisfy my requirement. Is there any other library I can use to get the week number in Actual Calendar ?
Are you talking about actual number of 7 day periods rather than which week number you're in? Keep in mind in 2016, Jan 3rd is the first day of the second week.
If you're looking at which 7 day period, you should simply count days since the beginning of the year and floor div by 7
dt = datetime.datetime(year=2016, month=1, day=2)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
The 29th should be the first day of week 5. Let's try it.
dt = datetime.datetime(year=2016, month=1, day=29)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
# 5

Calculate number of days for last 6months from today in python

In python how to find the total number of days for the last 6 months ?
For example today is 7 November(7 days in this month), and in october there are 31 days and so on until the last 6 months, and now i need to find the total for all the days in a month(until the last 6 months) like
7(Nov) + 31(Oct) + 30(Sep) +... until the last 6 months from now
with dateutil:
>>> from dateutil.relativedelta import relativedelta
>>> import datetime
>>> delta = relativedelta(months=6)
>>> six_month_away = datetime.date.today() - delta
>>> abs((six_month_away - datetime.date.today()).days)
184

Categories

Resources