Python - get elapsed time using datetime - python

With the datetime module, I can get the current time, like so:
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2017-08-29 23:01:32'
I have access to the time at which a file was created, in the same format:
>>> data['created']
'2017-08-29 20:59:09'
Is there a way, using the datetime module, that I can calculate the time between the two, in hours?

Performing subtraction on two datetime objects will result in a timedelta. You can use datetime.strptime to get that second datetime object, access the seconds attribute of that timedelta and calculate the hours from there:
from datetime import datetime
...
file_created = datetime.strptime(data['created'], '%Y-%m-%d %H:%M:%S')
difference = (datetime.now() - file_created).seconds
print("Hours since creation: " + str(difference // 3600)) # 3600 seconds in 1 hour

Related

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

How to parse datetime and time from strings and how to add these parsed datetime and time values in Python

I am parsing datetime objects from strings,
In these situation I faced a problem where I have to add datetime object with time object together to create combined timestamp.
I know there is a datetime.combine method but unfortunately I could not use it in this situation
e.g. there are two strings, one contains formatted datetime and other has formatted time like below
dt_str = "2018/11/27 14:12:32"
tm_str = "1:23:45.678" # 1 hour 23 minutes 11 seconds and 750 micro seconds
dt_str = "2018/11/27 14:12:32"
tm_str = "1:23:45.678"
First we need to import from python's standard libraries i.e. datetime, time and timedelta
import datetime, time
from datetime import timedelta
Then we will parse dt_str as datetime object and tm_str as time object
dt = datetime.datetime.strptime(dt_str, "%Y/%m/%d %H:%M:%S")
tm = time.strptime(tm_str, "%H:%M:%S.%f")
Now we will use timedelta class to add hours, minutes and seconds to the datetime object from time object
timestamp = dt + timedelta(hours=tm.tm_hour) + \
timedelta(minutes=tm.tm_min) + timedelta(seconds=tm.tm_sec)
Results
print("dt:", dt)
print("tm:", tm)
print("timestamp: ", timestamp)
Note: You can not add microseconds value, at least I do not know the method. If someone knows better way to do above operations please put your solutions below
dt: 2018-11-27 14:12:32
tm: time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=23, tm_sec=45, tm_wday=0, tm_yday=1, tm_isdst=-1)
timestamp: 2018-11-27 15:36:17

Seconds since date (not epoch!) to date

I have a dataset file with a time variable in "seconds since 1981-01-01 00:00:00".
What I need is to convert this time into calendar date (YYYY-MM-DD HH:mm:ss).
I've seen a lot of different ways to do this for time since epoch (1970) (timestamp, calendar.timegm, etc) but I'm failing to do this with a different reference date.
I thought of doing something that is not pretty but it works:
time = 1054425600
st = (datetime.datetime(1981,1,1,0,0)-datetime.datetime(1970,1,1)).total_seconds()
datetime.datetime.fromtimestamp(st+time)
But any other way of doing this will be welcome!
You could try this:
from datetime import datetime, timedelta
t0 = datetime(1981, 1, 1)
seconds = 1000000
dt = t0 + timedelta(seconds=seconds)
print dt
# 1981-01-12 13:46:40
Here t0 is set to a datetime object representing the "epoch" of 1981-01-01. This is your reference datetime to which you can add a timedelta object initialised with an arbitrary number of seconds. The result is a datetime object representing the required date time.
N.B. this assumes UTC time

Turn number representing total minutes into a datetime object in python

If I have a number representing a period I am interested in, for example the number 360 representing 360 minutes or 6 hours, how do I turn this into a datetime object such that I can perform the standard datetime object functions on it?
Similarly, if I have a datetime object in the format 00:30:00, representing 30 minutes, how do I turn that into a normal integer variable?
import datetime
t = datetime.timedelta(minutes=360)
This will create an object, t, that you can use with other datetime objects.
To answer the 2nd question you just edited in, you can use t.total_seconds() to return whatever your timedelta holds back into an integer in seconds. You'll have to do the conversion to minutes or hours manually though.
You may want to look at time deltas:
delta = datetime.timedelta(minutes=360)
If your time data is in '00:30:00' format then you should use strptime
>>> from datetime import datetime
>>> time = '00:30:00'
>>> datetime.strptime(time, '%H:%M:%S).time()
datetime.time(0, 30)
If your data is in 30 (integer) format
>>> from datetime import datetime, timedelta
>>> from time import strftime, gmtime
>>> minutes = timedelta(minutes=360)
>>> time = strftime('%H:%M:%S', gmtime(minutes.total_seconds()))
>>> datetime.strptime(time, '%H:%M:%S').time()
datetime.time(6, 0)

How can I convert HH:MM:SS string to UNIX epoch time?

I have a program (sar command line utility) which outputs it's lines with time column. I parse this file with my python script and I would like to convert sar's 02:31:33 PM into epochs e.g. 1377181906 (current year, month and day with hours, minutes and seconds from abovementioned string). How can this done in a less cumbersome way? I tried to do this by myself, but stuck with time/datetime and herd of their methods.
Here's one way to do it:
read the string into datetime using strptime
set year, month, day of the datetime object to current date's year, month and day via replace
convert datetime into unix timestamp via calendar.timegm
>>> from datetime import datetime
>>> import calendar
>>> dt = datetime.strptime("02:31:33 PM", "%I:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> calendar.timegm(dt.utctimetuple())
1377138693
Note that in python >= 3.3, you can get the timestamp from a datetime by calling dt.timestamp().
Also see:
Python Create unix timestamp five minutes in the future
An another way to have epoch time is to use mktime from time module and pass time tuple of date, so you can do this:
>>> from datetime import datetime
>>> from time import mktime
>>> dt = datetime.strptime("02:31:33 PM", "%H:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> int(mktime(dt.timetuple()))
1377131493

Categories