python check datetime is older then n days? - python

I am given a date as string,for example '2019-10-29T10:31:58.000Z'.
I want to check if this date and time is older then 5 days from the current date and time.
What is the best way to check this?
All other related threads I found had a different datetime format.

The format is ISO8601 (with a Z for a zero timezone), so...
>>> import datetime
>>> s = '2019-10-29T10:31:58.000Z'
>>> dt = datetime.datetime.fromisoformat(s.rstrip('Z'))
>>> days_since = (datetime.datetime.now() - dt).total_seconds() / 86400.0
>>> print(days_since)
2.1420510361689815 # (at the time of writing)

Related

How to use milliseconds instead of microsenconds in datetime python

A client has specified that they use DateTime to store their dates using the format 2021-06-22T11:17:09.465Z, and so far I've been able only to obtain it in string dates, because If I want to maintain the milliseconds it saves them like 2021-06-22T11:17:09.465000.
Is there any possible way to force DateTime to use milliseconds instead of microseconds? I'm aware of the %f for microseconds in the format, but I've tried everything I can think of to reduce those 3 decimals while keeping it DateTime with no results however.
I suggest to use the timespec parameter, as described in python docs https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat:
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> datetime.now().isoformat(timespec='milliseconds')
'2021-12-02T14:03:57.937'
Something like this works:
from datetime import datetime
dt = datetime.now()
print(f"{dt:%Y/%m/%dT%H:%M:%S}.{f'{dt:%f}'[:3]}")
Hope I help.
I assume you're looking for this? See also my general comment at question.
The variable 3 in [:3] can be adjusted to your liking for amount of zeros in ms to ns range. Use the type() to show you its a DateTime object.
import time
from datetime import datetime
tm = time.time()
print(tm)
dt = str(tm).split('.')
print(dt)
timestamp = float(dt[0] + '.' + dt[1][:3])
dt_object = datetime.fromtimestamp(timestamp)
print(dt_object)
This prints for example:
tm : 1638463260.919723
dt : ['1638463260', '919723']
and
dd_object : 2021-12-02 17:41:00.919000
You can divide nanoseconds by 1000000000 to get seconds and by 1000000 to get milliseconds.
Here is some code that will get nanoseconds:
tim = time.time_ns()
You can then combine the output of this with the rest of the format. Probably not the cleanest solution but it should work.

Change datetime into integer

I am using Python in dynamo and I am facing a problem.
I have to convert date time into integer so I could further process
it
I have tried some codes but they are not helpful.
If you'd like to convert the datetime to a unix timestamp (number of seconds elapsed since Jan 1, 1970), then you can do
>>> import datetime as dt
>>> ts = dt.datetime.now()
>>> print(int(ts.timestamp())
1588967243
Maybe you want to get timestamp?
import time
import datetime
s = "01/12/2011"
time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
Result: 1322697600.0

How to minus time that received from API server and current time in Python

Kindly help below my query:
I got an estimated time from API server like below:
2019-09-25T20:11:23+08:00
it seems like iso 8601 standard with timezone.
I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.
import datetime
Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()
left_days =
left_hour =
left_min =
left_sec =
Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7
import datetime
received = datetime.datetime.fromisoformat(Receved_time_frim_API)
In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like
>>> date, timezone = Receved_time_frim_API.split("+")
>>> tz_hours, tz_minutes = timezone.split(":")
>>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
>>> date -= datetime.timedelta(hours=int(tz_hours))
>>> date -= datetime.timedelta(minutes=int(tz_minutes))
Note that this will work only in case of positive timezones
To substract two datetime objects use
td = date - Current_time
left_days = td.days
left_hour = td.seconds // 3600
left_min = (td.seconds//60)%60
left_sec = td.seconds % 60
Okay first you need to parse the Receved_time_frim_API into datetime format:
from dateutil import parser
Receved_time_frim_API = parser.parse("2019-09-25T20:11:23+08:00")
But you can't just substract this from your Current_time, because datetime.now() is not aware of a timezone:
from datetime import timezone
Current_time = datetime.datetime.now().replace(tzinfo=timezone.utc)
print (Current_time-Receved_time_frim_API)
The result is a datetime.timedelta

Converting datetime to strptime

I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).

Working with time values greater than 24 hours

How does one work with time periods greater than 24 hours in python? I looked at the datetime.time object but this seems to be for handling the time of a day, not time in general.
datetime.time has the requirement of 0 <= hour < 24 which makes it useless if you want to record a time of more than 24 hours unless I am missing something?
Say for example I wanted to calculate the total time worked by someone. I know the time they've taken to complete tasks individually. What class should I be using to safely calculate that total time.
My input data would look something like this:
# The times in HH:MM:SS
times = ["16:35:21", "8:23:14"]
total_time = ? # 24:58:35
Unfortunately there is not a builtin way to construct timedeltas from strings (like strptime() for datetime objects) so we have to build a parser:
>>> from datetime import timedelta
>>> import re
>>> def interval(s):
"Converts a string to a timedelta"
d = re.match(r'((?P<days>\d+) days, )?(?P<hours>\d+):'
r'(?P<minutes>\d+):(?P<seconds>\d+)', str(s)).groupdict(0)
return timedelta(**dict(((key, int(value)) for key, value in d.items())))
>>> times = ["16:35:21", "8:23:14"]
>>> print sum([interval(time) for time in times])
1 day, 0:58:35
EDIT: Old wrong answer (where I misread the question):
If you substract datetimes you get a timedelta object:
>>> import datetime as dt
>>> times = ["16:35:21", "8:23:14"]
>>> fmt = '%H:%M:%S'
>>> start = dt.datetime.strptime(times[1], fmt )
>>> end = dt.datetime.strptime(times[0], fmt)
>>> diff = (end - start)
>>> diff.total_seconds()
29527.0
>>> (diff.days, diff.seconds, diff.microseconds)
(0, 29527, 0)
>>> print diff
8:12:07
As I understand, you want a sum of all times and not difference. So you can convert your time to timedelta and then sum it:
>>> from datetime import timedelta
# get hours, minutes and seconds
>>> tm1 = [map(int, x.split(':')) for x in times]
# convert to timedelta
>>> tm2 = [timedelta(hours=x[0], minutes=x[1], seconds=x[2]) for x in tm1]
# sum
>>> print sum(tm2, timedelta())
1 day, 0:58:35

Categories