Python - Subtracting a specific date-time from current GMT date-time - python-2.7

I'm trying to do some time math, but I'm not sure how I could do this. I'd like to subtract a specific date & time I have in a string (e.g.: 15:54:00 2017-5-20) from current GMT time (e.g: 20:06:27 2017-12-22).
Any thoughts on how I could do this?
# import data into Python
with open(output_file2) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
# here, objects [0][4] and [0][5] would be, for instance: 15:54:00 and 2017-5-20
# , respectively
# UTC Time
os.system("date -u \"+%H:%M:%S %Y-%m-%d\" | gawk '{print \" UTC Date & Time: \", $1, \"\", $2}'")
# eg.: 20:06:27 2017-12-22
Any thoughts would be great! Thanks =)
Update: I've tried so far:
UTC_time = datetime.datetime.utcnow().strftime("%H:%M:%S %Y-%m-%d")
print ' UTC Date & Time: ', UTC_time
time1 = d[0][4]
date1 = d[0][5]
mytime = time1, date1
time_difference = datetime.datetime.utcnow() - mytime
print "HELLO", time_difference
but I keep getting an error:
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'tuple'
Not sure what I am doing wrong...

Your mytime variable is not a datetime.datetime object and cannot be used to operate against one. Instead of mytime = time1, date1 you are looking for something more along the lines of
my_date_str = "{} {}".format(time1, date1)
mytime = datetime.datetime.strptime(my_date_str, "%H:%M:%S %Y-%m-%d")
Do realize that in spite of using utcnow() the resulting datetime.datetime object is NOT timezone aware, and neither is mytime. So any math between the two is pure clock math, no timezones taken into account.
If you require timezone support, look into pytz or Pendulum or perhaps find another if they don't suit you.

Related

How to handle datetime vlaues in python?

I have a datetime in format = '2020-05-01'. I want the output to be 2020-05-01 00:00:00.
I use this simple code to achieve this but I am missing the time part.
datetime.strptime(month, "%Y-%m-%d")
I am using python2. Does anyone have any idea on how to achieve this. This seems like a really simple problem but for some reason I am not able to achieve it.
Your one line of code already generates a datetime value which should be set to midnight (the default value for no explicit time component). If you want to view this data with its time component, then use strftime with an appropriate format mask:
month = '2020-05-01'
dt = datetime.strptime(month, "%Y-%m-%d")
dt_out = dt.strftime("%Y-%m-%d %H:%M:%S")
print(dt_out)
This prints:
2020-05-01 00:00:00
x = datetime.strptime(month, "%Y-%m-%d")
x.strftime(month, "%Y-%m-%d %H:%M:%S")
Source:
https://www.programiz.com/python-programming/datetime/strftime

Subtracting two datetimes from each other and returning in HH:MM:SS in python 2.7

I have two date-time strings that I wish to subtract from each other and want to return a answer in
the HH:MM:SS format using python 2.7. For Example I have "2019-01-22 10:46:34" and "2019-01-22 10:30:34" and want it to return something like this 00:16:00. I have tried converting the times to integers but can't seem to convert back. I have also tried the datetime module. Below is a rudimentary example of something I tried that I wish to convert into a function.
from datetime import datetime
a = "2019-01-22 10:46:34"
b = "2019-01-22 10:30:25"
c = a-b
print(datetime.time(c, '%Y-%m-%d %H:%M:%S')
I have been working on this problem for a few days so any help would be much appreciated.
Take a look at the timedelta Object.
With that you can get the difference of two datetime Objects in Seconds and then you can calc the Minutes Hours etc.
Example you have two datetime objects a and b, c will be the timedelta object:
import datetime
# datetime object (year, month, day, hour, minute, second)
a = datetime.datetime.strptime("2019-01-22 10:46:34", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("2019-01-22 10:30:25", "%Y-%m-%d %H:%M:%S")
# returns timedelta object
c = a-b
print('Difference: ', c)
# return (minutes, seconds)
minutes = divmod(c.seconds, 60)
print('Difference in minutes: ', minutes[0], 'minutes',
minutes[1], 'seconds')
EDIT: divmod() is used to get batter result in terms of minutes and seconds, but you could also just write
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
Output: Difference in minutes: 16 minutes 9 seconds

datetime strptime method for format HH:MM:SS.MICROSECOND

I'm trying to investigate the Python time striptime method to decompose a time represented as 11:49:57.74. The standard %H, %M, %S are able to decompose the hour , minute , second. However, since the data is a string ( which is taken in python pandas column as datatype object, the Milliseconds after the decimal second is left uninterpreted. Hence, I get an error. Could someone please advise how to parse the example so that the seconds and microseconds are correctly interpreted from the time string ?
I would then use them to find the time delta between two time stamps.
I don't know if I had correctly understood your question.
So, to convert that string time to datetime and calculate the timedelta between two times you need to do as follow:
timedelta = str() #declare an empty string where save the timedelta
my_string = '11:49:57.74' # first example time
another_example_time = '13:49:57.74' #second example time, invented by me for the example
first_time = datetime.strptime(my_string, "%H:%M:%S.%f") # extract the first time
second_time = datetime.strptime(another_example_time , "%H:%M:%S.%f") # extract the second time
#calculate the time delta
if(first_time > second_time):
timedelta = first_time - second_time
else:
timedelta = second_time - first_time
print "The timedelta between %s and %s is: %s" % (first_time, second_time, timedelta)
Here obviusly you don't have any date, so the datetime library as default use 1900-01-01 as you can see in the result of the print:
The timedelta between 1900-01-01 11:49:57.740000 and 1900-01-01 13:49:57.740000 is: 2:00:00
I hope this solution is what you need. Next time provide a little bit more information please, or share an example with the code that you have tried to write.

python - Difference between two unix timestamps

I have two timestamps in miliseconds and i want to compute the difference between the two in minutes:
d1 = 1502053449617
current_time_utc = int(round(time.time() * 1000))
The values for d1 are dynamically generated by a third party API and are in UTC . I am trying to get the difference between the current time in UTC and d1.
fmt = '%Y-%m-%d %H:%M:%S'
time1 = datetime.strptime(d1, fmt)
time2 = datetime.strptime(current_time_utc, fmt)
I want to be able to find the difference between the two (time1 - time2) . If i do the below , i get an error saying "string expected, long given"
print( time1-time2)
I want the difference between the two in minutes . Please help
You don't need to format the string, you just need to convert the timestamp directly, by first dividing it by 1000. Then its just a matter of printing out the differences (and calculating it in minutes):
from __future__ import division
import datetime
d1 = 1502053449617
converted_d1 = datetime.datetime.fromtimestamp(round(d1 / 1000))
current_time_utc = datetime.datetime.utcnow()
print((current_time_utc - converted_d1))
print((current_time_utc - converted_d1).total_seconds() / 60)
The above prints:
3 days, 5:08:14.087515
4628.234791916667
I had to calculate the difference between two unix timestamps - but in days, as follows:
create two unix timestamps:
import datetime
timestamp1 = datetime.datetime(2017, 12, 1).strftime('%s')
timestamp2 = datetime.datetime(2017, 11, 14).strftime('%s')
print(timestamp1)
print(timestamp2)
1512079200
1510610400
calculate the day difference:
print((float(timestamp1)-float(timestamp2))/(60*60*24))
output:
17.0

How to convert time.strptime into an integer for datatime.date() Python 2

How would I convert the result from strptime into an integer value or a value that can be used by date.date()?
convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = datetime.datetime(convertTOdate)
A Solution on stackoverflow was to do:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(struct))
I do not want to get the local time as it would not work with my function
I am using Python 2
Thank you
You can use the following approach.
from datetime import datetime
def time_in_seconds(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
convertTOdate = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = time_in_seconds(convertTOdate)
returns 1184752999.0 which is equivalent to 2007-07-18 10:03:19
duedate = datetime.utcfromtimestamp(duedate)
print duedate
Just remember before using the following two:
fromtimestamp give you the date and time in local time and utcfromtimestamp gives you the date and time in UTC.