from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now
time.sleep(5)
d2 = datetime.now
diff = (d2-d1).seconds
print(diff)
i get the error message with
diff = (d2-d1).seconds
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'builtin_function_or_method'
how to different the two datetime in seconds format?
You are missing your brackets () after now:
from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now()
time.sleep(5)
d2 = datetime.now()
diff = (d2-d1).seconds
print(diff)
now is a function, so what you are trying to subtract are two functions. Try this:
datetime.now() - datetime.now()
The problem is that you are not calling the datetime.now function, you are merely assigning d1 and d2 to the reference of the function. This should solve your problem:
d1 = datetime.now() # note the function call
d2 = datetime.now()
Related
I am trying to set a function that subtracts a month from an specific date format as an argument, and returns a date in the same specific date format,
This argument is given by today's month and year: 01/%m/%Y.
Actual code:
from datetime import datetime
import dateutil.relativedelta
actual_date = datetime.now()
actual_date = "{}/{}/{}".format('01', actual_date.month, actual_date.year)
def set_date(actual_date):
print(actual_date - dateutil.relativedelta.relativedelta(months=1))
Here's the output when set_date() is tested:
set_date(actual_date)
TypeError: unsupported operand type(s) for -: 'str' and 'relativedelta'
Expected output should look like this:
01/12/2020
You're doing it in the wrong order. Perform the date calculation first, and then convert to a string.
now = datetime.now()
one_month_ago = now - dateutil.relativedelta.relativedelta(months=1)
print("{}/{}/{}".format('01', one_month_ago.month, one_month_ago.year))
In the first line, you get a datetime, then in the second line you build a string out of it. As a result, in set_date you get the mentioned error.
I suggest that you remove the second line and simply give the datetime object to set_date and do a strftime on the result:
actual_date = datetime.now()
def set_date(actual_date):
result = actual_date - dateutil.relativedelta.relativedelta(months=1)
print(datetime.strftime(result, "01/%m/%Y"))
However, if you really want to keep those conversions, you can use strptime for that purpose.
actual_date = datetime.now()
actual_date = datetime.strptime("{}/{}/{}".format('01', actual_date.month, actual_date.year), "%d/%m/%Y")
def set_date(actual_date):
result = actual_date - dateutil.relativedelta.relativedelta(months=1)
print(datetime.strftime(result, "%d/%m/%Y"))
From what I've seen this should be working even if it's not the prettiest. I've tried plenty of things but doesn't seem to work with anything and best I've been able to do is change the error message lol.
try:
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
Try the following:
from datetime import timedelta
import datetime as dt
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1 = d1.strftime('%Y%m%d') # I changed this line
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
strftime() returns the string, it does not convert the date itself to a string.
I modified your code a little. There were a couple of mistake in it and it wasn't running.
The main problem you were running into is you were trying to concatenate a string with a datetime object. You applied the strftime correctly but you didn't save the string. That string you can concatenate with another string.
import datetime as dt
date = dt.datetime.now()
d1 = date - dt.timedelta(days=1)
d1_string = d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol{timestamp}.txt'.format(timestamp=d1_string)
In your code you don't assign result of datetime.strftime() to a variable. Solution is simple:
from datetime import datetime, timedelta
current_date = datetime.now() # store current date and time
required_date = current_date - timedelta(days=1) # substitute 1 day
str_date = required_date.strftime('%Y%m%d') # apply formatting
url = f'http://regsho.finra.org/FNQCshvol{str_date}.txt'
You can also do it in one line (which makes code much less readable):
url = f"http://regsho.finra.org/FNQCshvol{(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')}.txt"
I need to add a given number of minutes or seconds to a Time object that comes without the date portion.
For Ex:
Time: 13:00:00 + 10 minutes (Should return 13:10:00)
Time: 21:50:00 + 1800 seconds (Should return 22:20:00)
My code:
from datetime import timedelta
d = timedelta(minutes=30)
calendar_entry + d #calendar_entry is a time object HH:MM:SS
Error:
During handling of the above exception (unsupported operand type(s)
for +: 'datetime.time' and 'datetime.timedelta'), another exception
occurred:
How can I do this in Python 3?
Try this:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(13, 0)) + timedelta(minutes=10)
print (dt.time())
#13:10:00
Here's what you want:
import datetime
date = datetime.datetime.strptime('15:57:12', '%H:%M:%S')
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(seconds=1800)
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(minutes=30)
print(date.strftime('%H:%M:%S'))
Output:
15:57:12
16:27:12
16:57:12
This way of manipulation is only possible with datetime objects, but luckily, you can do the conversion from datetime to time, to have it your way. Take a look at add_minutes:
import datetime
def add_minutes(tm, minutes1):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(minutes=minutes1)
return fulldate.time()
a = datetime.datetime.now().time()
b = add_minutes(a, 2)
print(a)
print(b)
being inexperienced with Python I am unable to properly deal with the datetime objects, when wanting to iterate over them. I imported timestamps from a csv file and parsed them into datetime objects. Now I am unable to perform functions on them, because I get one error after the other. Please see my code, what causes the "TypeError: 'datetime.datetime' object is not iterable".
If there is no simple solution to my problem, can someone tell me how to save the datetime objects into a list?
The function of my code is inspired by this post, which works on date time objects from a list: Getting the closest date to a given date
Thanks in advance.
from datetime import datetime, timedelta
import pandas as pd
from dateutil.parser import parse
csvFile = pd.read_csv('myFile.csv')
column = csvFile['timestamp']
column = column.str.slice(0, 19, 1)
dt1 = datetime.strptime(column[1], '%Y-%m-%d %H:%M:%S')
print("dt1", dt1) #output: dt1 2010-12-30 15:06:00
dt2 = datetime.strptime(column[2], '%Y-%m-%d %H:%M:%S')
print("dt2", dt2) #output: dt2 2010-12-30 16:34:00
dt3 = dt1 - dt2
print("dt3", dt3) #output: dt3 -1 day, 22:32:00
#parsing the timestamps as datetime objects works:
for row in range(len(column)):
timestamp = datetime.strptime(column[row], '%Y-%m-%d %H:%M:%S')
print("timestamp", timestamp) #output (excerpt): timestamp 2010-12-30 14:32:00 timestamp 2010-12-30 15:06:00
here error occurs:
base_date = dt1
def func(x):
d = x[0]
delta = d - base_date if d > base_date else timedelta.max
return delta
min(timestamp, key = func)
timestamp is an instance of datetime.datetime,you should put it into a list or a tuple.
after correct,it should be like this min([timestamp], key = func)
TypeError: strptime() argument 1 must be str, not datetime.date
I'm getting the above error when I run the below code. Do you have any idea about this ?
import datetime
from datetime import datetime, timedelta
import babel
import time
date_format = "%Y-%m-%d"
class HrPayslipEmployees(models.TransientModel):
_inherit = 'hr.payslip.employees'
#api.one
def compute_date_diff(self, ds, dt):
from datetime import datetime
d1 = datetime.strptime(ds, "%Y-%m-%d")
d1 = str(d1)
d2 = datetime.strptime(dt, "%Y-%m-%d")
d2 = str(d2)
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
But the same code is perfectly working in the Pythin 2.7 , but the above code is I run on Python 3.x
Imported libraries for the program are also mentioned above.
Thanks in advance. The complete code is just above here.
import datetime
from datetime import datetime, timedelta
date_format = "%Y-%m-%d"
def compute_date_diff( ds, dt):
d1 = datetime.strptime(ds, "%Y-%m-%d")
d2 = datetime.strptime(dt, "%Y-%m-%d")
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
print(compute_date_diff("2019-03-24","2019-03-25"))
This is working fine in python3. You don't need to convert d1 and d2 to string for finding days.
You do not have to convert the date to str:
In Python 3.x:
from datetime import datetime
def compute_date_diff(ds, dt):
d1 = datetime.strptime(ds, "%Y-%m-%d")
d2 = datetime.strptime(dt, "%Y-%m-%d")
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
print(compute_date_diff('2019-01-01', '2019-02-01'))
OUTPUT:
32
Let me answer in Odoo context. With this commit your old code isn't working anymore. Because before that, you got strings as values for Date and Datetime fields in Odoo. As of this commit you get python datetime.date resp. datetime.datetime objects instead.
So just use these objects and don't parse into or from strings if not needed.