Why the output of this relativedelta attribute is also zero?
The data file contains two date time strings, the purpose is to get the time difference between the two.
# python3.6 time_diff.py
0
0
0
0
# cat data
06/21/2019 21:45:24 06/21/2020 21:45:26
06/21/2019 22:42:25 06/22/2020 01:28:41
06/21/2019 22:41:32 06/21/2020 22:42:32
06/20/2019 23:42:25 06/22/2020 02:42:29
# cat time_diff.py
import dateutil.relativedelta, datetime
f = open("data", "r")
for line in f:
t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
rd = dateutil.relativedelta.relativedelta(t1, t2)
print(rd.seconds)
instead of
t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
go with
t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[2] + " " + line.split()[3], "%m/%d/%Y %H:%M:%S")
you are providing wrong input to t2. After splitting the input from the file becomes this ['06/21/2019', '21:45:24', '06/21/2020', '21:45:26'].
So t1 should get input 0 and 1 and t2 should get input 2 and 3.
Below is the updated code:
import dateutil.relativedelta, datetime
f = open("data", "r")
for line in f:
t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[2] + " " + line.split()[3], "%m/%d/%Y %H:%M:%S")
rd = dateutil.relativedelta.relativedelta(t1, t2)
print(t1, t2, rd.seconds)
Related
i am trying to get the time difference using two times. i am getting 2 epoch timestamps from an api, converting them to a datetime, and then trying to compare them and get the time difference in minutes.
No errors in console.. the minutes just stay at 0.0 when i return it.
onlinestatus = (data["session"]["online"])
if onlinestatus is False:
theNewLineString = "\n"
lastLogout_string = "LastLogout: "
log_in = int(data2["player"]["lastLogin"])
log_out = int(data2["player"]["lastLogout"])
log_in_converted = timedate = time.strftime('%Y-%m-%d\n%I:%M %p', time.localtime(log_in / 1000))
log_out_converted = timedate = time.strftime('%Y-%m-%d\n%I:%M %p', time.localtime(log_out / 1000))
diff = datetime.strptime(log_in_converted, '%Y-%m-%d\n%I:%M %p') - datetime.strptime(log_out_converted, '%Y-%m-%d\n%I:%M %p')
return str("Online: ") + "`" + "False" + "`" + theNewLineString + theNewLineString + lastLogout_string + "`" + log_out_converted + theNewLineString + "`" + "Minutes Since Last Logout: " + "`" + str(diff.seconds/60) + "`"
I know everything else works. I am using a discord bot to return everything and here is what it returns:
Online: False
LastLogout: 2020-05-16
12:27 PM
Minutes Since Last Logout: 0.0
Any help is appreciated!
Let's say you have 2 datetime objects:
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()
Now you can substract one from the other:
(d2 - d1)
This gives the result:
datetime.timedelta(seconds=3, microseconds=516614)
Then you can call the 'seconds' item and convert it to minutes:
(d2 - d1).seconds / 60
Hope this helps.
I am a beginner to python and I have this date and time code from shell script, and how do I make it into python, also how can I take date from last month till now
ToDay=`date "+%Y%m%d"`
CheckDATE=`date "+%Y-%m-%d" --date '1 day ago'`
NOWDATE=`date "+%Y-%m-%d"`
This is the python code
from datetime import datetime, date, timedelta
progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":1},{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":4}]}]}]},\\"scope\\":\\"global\\",\\"size\\":1,\\"from\\":0,\\"sort\\":{\\"create_date\\":{\\"order\\":\\"desc\\"}}}" > ' + ResultDir + 'srciplist-' + ToDay + '.json'
ToDay = datetime.now().strftime('%Y%m%d')
CheckDATE = datetime.strptime("2017-12-01", "%Y-%m-%d").date()
NOWDATE = datetime.now().date()
Error:
progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":1},{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":4}]}]}]},\\"scope\\":\\"global\\",\\"size\\":1,\\"from\\":0,\\"sort\\":{\\"create_date\\":{\\"order\\":\\"desc\\"}}}" > ' + ResultDir + 'srciplist-' + ToDay + '.json'
TypeError: must be str, not datetime.date
>>> import datetime
>>> today = datetime.date.today()
>>> yesterday = today - datetime.timedelta(days=1)
>>> ToDay = today.strftime("%Y%m%d")
>>> CheckDATE = yesterday.strftime("%Y-%m-%d")
>>> NOWDATE = today.strftime("%Y-%m-%d")
>>> print ToDay
20180126
>>> print CheckDATE
2018-01-25
>>> print NOWDATE
2018-01-26
You can convert date using the following code:
CheckDATE = datetime.datetime.strptime("2017-12-01", "%Y-%m-%d").date()
ToDAY = datetime.datetime.now().strftime("%Y-%m-%d")
CheckDATE = CheckDATE.strftime("%Y-%m-%d")
Adding date at the end only outputs the date part and omits time.
I hope this answers your question.
Edit: Updated based on additional information.
I'm working on my python script to get the strings from the button objects so I can use it to set the date formats with the time that I got from the strings to store it in the lists. When I get the strings from the button objects, I want to set the date for each string, example: 29/08/2017 11:30PM, 30/08/2017 12:00AM, 30/08/2017 12:30AM.
When I try this:
if day_date >= 0 and day_date <= 6:
if epg_time3 == '12:00AM':
if day_date > 0:
currentday = datetime.datetime.now() + datetime.timedelta(days = 0)
nextday = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
if currentday != nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
elif currentday == nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
It will show the output:
self.epg_time_1
['29/08/2017 11:00PM']
self.epg_time_2
['29/08/2017 11:30PM']
self.epg_time_3
['29/08/2017 12:00AM']
When I'm calling the EPG_Times function again, it will show the output like this:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['30/08/2017 12:00AM']
It should be:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['31/08/2017 12:00AM']
As you can see the time 12:00AM is the next day so I want to set it to 31 not 30. I have changed from days = self.program_day + 1 to days = self.program_day - 1, but when the strings show 11:00PM, 11:30PM and 12:00AM from the variables epg_time_1, epg_time_2 and epg_time_3, it will show the output like this:
self.epg_time_1
['30/08/2017 11:00PM']
self.epg_time_2
['30/08/2017 11:30PM']
self.epg_time_3
['30/08/2017 12:00AM']
Here is the full code:
self.program_day = list()
def EPG_Times(self):
self.epg_time_1 = list()
self.epg_time_2 = list()
self.epg_time_3 = list()
epg_time1 = str(self.getControl(344).getLabel())
epg_time2 = str(self.getControl(345).getLabel())
epg_time3 = str(self.getControl(346).getLabel())
day_date = self.program_day
day = ''
month = ''
year = ''
if day_date >= 0 and day_date <= 6:
if epg_time3 == '12:00AM':
if day_date == 0:
if epg_time1 == '12:00AM':
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
else:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
else:
currentday = datetime.datetime.now() + datetime.timedelta(days = 0)
nextday = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
if currentday != nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day + 1)
elif currentday == nextday:
epg_time_1 = datetime.datetime.now() + datetime.timedelta(days = self.program_day)
epg_time_2 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg_time_3 = datetime.datetime.now() + datetime.timedelta(days = self.program_day - 1)
epg1_day = epg_time_1.strftime("%d")
epg1_month = epg_time_1.strftime("%m")
epg1_year = epg_time_1.strftime("%Y")
epg2_day = epg_time_2.strftime("%d")
epg2_month = epg_time_2.strftime("%m")
epg2_year = epg_time_2.strftime("%Y")
epg3_day = epg_time_2.strftime("%d")
epg3_month = epg_time_2.strftime("%m")
epg3_year = epg_time_2.strftime("%Y")
half_hour = str(epg1_day + "/" + epg1_month + "/" + epg1_year + " " + epg_time1)
one_hour = str(epg2_day + "/" + epg2_month + "/" + epg2_year + " " + epg_time2)
one_hour_half = str(epg3_day + "/" + epg3_month + "/" + epg3_year + " " + epg_time3)
#Store the times and date in the list....
self.epg_time_1.append(half_hour)
self.epg_time_2.append(one_hour)
self.epg_time_3.append(one_hour_half)
What I'm expected the code to do is to change to the previous day date for each string that I get from the button objects when I call the EPG_time(self) function. If the epg_time_1 and epg_time_2 show the strings 11:00PM and 11:30PM, I want to set the time and date to 29/08/2017 11:00PM for epg_time_1 and 29/08/2017 11:30PM for the epg_time_2. If the epg_time_3 show the string 12:00AM then I want to add it to the next day date with the time 30/08/2017 12:00AM.
In the next 24 hours if the epg_time_1 and epg_time_2 show the strings 11:00PM and 11:30PM, I want to set the time and date to 30/08/2017 11:00PM for epg_time_1 and 30/08/2017 11:30PM for the epg_time_2. If the epg_time_3 show the string 12:00AM then I want to set to the next day date with the time 1/09/2017 12:00AM
If the epg_time_1 and epg_time_2 show the strings 11:30PM and 12:00AM, I want to change to the previous date for epg_time_1 which it is 29/08/2017 11:30PM and 30/08/2017 12:00AM. It will be depends on the time and date when I have stored the strings in the list.
Can you please tell me an example how I could use to change the date to the previous date and add to the next day date using in python?
There's a lot of text in your question that makes it hard to pinpoint the issue exactly. However, it appears to boil down to adding a variable number of days to a particular date and ensuring that the month is also updated (if necessary).
You should use the datetime.datetime.strptime() method to convert your dates to datetimes, which makes it trivial to add timedelta (you use both timedelta and strftime but miss this crucial method) and then just convert back to a string.
import datetime as dt
def add_days(datelist, days_to_add):
# Convert the strings to datetime objects
datelist = [dt.datetime.strptime(item, '%d/%m/%Y %I:%M%p')
for item in datelist]
# Add a variable number of days (can be negative) to the datetimes
mod_dates = [item + dt.timedelta(days=days_to_add) for item in datelist]
# Convert back to strings
str_dates = [dt.datetime.strftime(item, '%d/%m/%Y %I:%M%p')
for item in mod_dates]
return str_dates
# This is the list right at the top of your question
a = ['29/08/2017 11:30PM', '30/08/2017 12:00AM', '30/08/2017 12:30AM']
print("Start:")
print(a)
b = add_days(a, 1)
print("After 1 call:")
print(b)
c = add_days(b, 1)
print("After 2 calls:")
print(c)
I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)
I need to do lots of conversation from string time stamp like '2012-09-08 12:23:33' into a seconds which is based on epoch time.Then i need to get time gap between two timestamp.I tried two different ways:
date1 = '2012-09-08'
time2 = '12:23:33'
timelist1 = map(int, date1.split('-') + time1.split(':'))
date2 = '2012-09-08'
time2 = '12:23:33'
timelist2 = map(int, date2.split('-') + time2.split(':'))
delta = datetime.datetime(*timelist2) - datetime.datetime(*timelist1)
print delta.seconds
The second way is:
date1 = '2012-09-08'
time1 = '12:23:33'
d1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
seconds1 = time.mktime(d1.timetuple())
....
seconds2 = time.mktime(d2.timetuple())
print seconds2-deconds1
However these two ways are not fast enough because I have almost 100 millions actions to do.Any suggestion?
You'd be much better off using the datetime.datetime.strptime() function, then subtract the two results:
import datetime
date1, time1 = '2012-09-08', '12:23:33'
date2, time2 = '2012-09-08', '12:23:33'
dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
print (dt1 - dt2).total_seconds()
Note that datetime.timedelta.seconds gives you just the remainder in seconds, there is also a .days attribute. Use .total_seconds() instead, it's much more convenient and saves you having to take the .days value into account.
Using the datetime.datetime.strptime() method, plus timedelta methods, is keeping the majority of the work in C code and should be faster.
Note that neither method is very fast because of the parsing step. Time tests:
>>> import timeit
>>> def parse_datetime():
... date1, time1 = '2012-09-08', '12:23:33'
... date2, time2 = '2012-09-08', '12:23:33'
... dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
... dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
... (dt1 - dt2).total_seconds()
...
>>> def parse_time():
... d1 = time.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
... d2 = time.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
... seconds1 = time.mktime(d1)
... seconds2 = time.mktime(d2)
... seconds1 - seconds2
...
>>> timeit.timeit('test()', 'from __main__ import parse_datetime as test', number=10000)
0.6590030193328857
>>> timeit.timeit('test()', 'from __main__ import parse_time as test', number=10000)
0.7742340564727783
where the second method just uses the time.strptime() function (which outputs a timetuple directly).
There are no faster avenues to parsing a date-time string that I am aware of though.