Skip to content
Advertisement

Tag: datetime

Checking date against date range in Python

I have a date variable: 2011-01-15 and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime. My working example is a “grace period”. A user logs into my site and if the grace period is

How to construct a timedelta object from a simple string

I’m writing a function that needs to parse string to a timedelta. The user must enter something like “32m” or “2h32m”, or even “4:13” or “5hr34m56s”… Is there a library or something that has this sort of thing already implemented? Answer For the first format (5hr34m56s), you should parse using regular expressions Here is re-based solution:

Trying to mock datetime.date.today(), but not working

Can anyone tell me why this isn’t working? Perhaps someone could suggest a better way? Answer There are a few problems. First of all, the way you’re using mock.patch isn’t quite right. When used as a decorator, it replaces the given function/class (in this case, datetime.date.today) with a Mock object only within the decorated function. So, only within your today()

Why does datetime.datetime.utcnow() not contain timezone information?

Why does this datetime not have any timezone info given that it is explicitly a UTC datetime? I would expect that this would contain tzinfo. Answer That means it is timezone naive, so you can’t use it with datetime.astimezone you can give it a timezone like this now you can change timezones To get the current time in a given

Most recent previous business day in Python

I need to subtract business days from the current date. I currently have some code which needs always to be running on the most recent business day. So that may be today if we’re Monday thru Friday, but if it’s Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some

User-friendly time format in Python?

Python: I need to show file modification times in the “1 day ago”, “two hours ago”, format. Is there something ready to do that? It should be in English. Answer The code was originally published on a blog post “Python Pretty Date function” (http://evaisse.com/post/93417709/python-pretty-date-function) It is reproduced here as the blog account has been suspended and the page is no

Python Date Comparisons

I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: This generates a type error. What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume

Advertisement