SpaceProgrammer
SpaceProgrammer

Reputation: 39

AttributeError: 'datetime.date' object has no attribute 'timestamp'

My code is:

get_closest_date = []
get_amounts_sum = []
query = """SELECT sp.customer_surname, sp.amount, cp.amount, sp.monthly, sp.date_ FROM set_payment7777 sp JOIN customers_payments7777 cp ON cp.customer_AFM = sp.customer_AFM  WHERE cp.date_ <= %s AND sp.date_ <= %s GROUP BY sp.customer_AFM"""
mycursor.execute(query,(to_date,to_date,))
for row in mycursor:
    get_closest_date.append(row[4])
                        


cloz_dict = {abs(datetime(int(to_year_drop.get()), int(to_month_drop.get()), int(to_day_drop.get())).timestamp() - date.timestamp()) : date for date in get_closest_date}
res = cloz_dict[min(cloz_dict.keys())]

print(res)

and my imports are:

from tkinter import *
from tkinter import messagebox
import os 
import mysql.connector
from tkinter import ttk
from datetime import date
from datetime import datetime

but I keep getting: AttributeError: 'datetime.date' object has no attribute 'timestamp'

Upvotes: 1

Views: 5051

Answers (1)

FObersteiner
FObersteiner

Reputation: 25684

date objects have no .timestamp() method as a datetime object has. As a work-around, you can create a datetime object from it by using combine:

from datetime import date, datetime

d = date(2020, 1, 1)
dt = datetime(2020, 1, 1) # for comparison

print(dt.timestamp())
print(datetime.combine(d, datetime.min.time()).timestamp())
# 1577833200.0
# 1577833200.0

date objects have a fromtimestamp method, so the lack of the inverse actually seems inconsistent to me. Just as that would truncate the time information given by the timestamp, a timestamp method would have to implicitly use a time - e.g. 0 hours in the local time zone (as date objects are naive). If anybody has a good explanation, please comment :)

Upvotes: 2

Related Questions