problems with data in python - python

I have code in django:
for i in range(int(cac)):
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M") - datetime.timedelta(minutes=i)
and have some of this errors :
type object 'datetime.datetime' has no attribute 'datetime'
or
type object 'datetime.time' has no attribute 'mktime'
or somethings else.
I try few examples:
import datetime
import time
or
from datetime import datetime
or
from datetime import *
from time import *
explain me what I do wrong?
thanks

Check all your imports. If you import in models like
from datetime import datetime
and then import
from .models import *
so you will have errors like this. Check all your imports.

Try this:
import datetime
for i in range(int(cac)):
print (datetime.datetime.now() - datetime.timedelta(minutes=i)).strftime('%Y-%m-%d %H:%M')

Related

AttributeError: module 'datetime' has no attribute 'datetime'

import datetime
current_datetime_demo = datetime.datetime.today()
print(current_datetime_demo)
I am using pycharm to run this and it keeps throwing this error when i try to print date and time
if you already imported datetime library you should do
current_datetime_demo = datetime.today()

import datetime - Clarification

''''
from datetime import datetime
now = datetime.now().time()
print(now)
o/p: 21:44:22.612870
''''
But, when i am trying:
''''
import datetime
now = datetime.now().time()
print(now)
''''
it give following error:
Traceback (most recent call last):
File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in
now = datetime.now().time() # time object
AttributeError: module 'datetime' has no attribute 'now'
any one explain what is difference between both?
The datetime library exports a module called datetime.
Modules are Python .py files that consist of Python code. Any Python file can be referenced as a module.
if you want you can also use it this way:
import datetime
datetime.datetime.now()

Error: column is of type timestamp without time zone but expression is of type double precision

The following code...
import time
import numpy as np
import pyodbc
import datetime
import win32com.client
import pythoncom
import re
from sqlalchemy import create_engine, event
import pandas as pd
import runpy
import codecs
import collections
from multiprocessing import Process, Queue
from datetime import datetime, timezone, timedelta
import threading
import os
import csv
import warnings
import xlsxwriter
from threading import Timer
import psycopg2
warnings.filterwarnings("ignore")
import time
import win32com.client
import threading
from datetime import datetime, timezone, timedelta
import numpy as np
import pyodbc
import datetime
import pandas as pd
import runpy
import codecs
import collections
from multiprocessing import Process, Queue
import threading
from datetime import timedelta
import warnings
from win32com import client
from datetime import datetime
import os
#from docx import Document
#from docx.shared import Inches, Pt, Mm
import time
import numpy as np
import pyodbc
import datetime
import pandas as pd
import runpy
import codecs
import collections
from multiprocessing import Process, Queue
import threading
from datetime import timedelta
from datetime import datetime
import os
import time
import glob
import time
import time
from datetime import datetime, timezone, timedelta
import time
import win32com.client
import threading
from datetime import datetime, timezone, timedelta
import numpy as np
import pyodbc
import datetime
import pandas as pd
import runpy
import codecs
import collections
from multiprocessing import Process, Queue
import threading
from datetime import timedelta
import warnings
from win32com import client
from datetime import datetime
import os
#from docx import Document
#from docx.shared import Inches, Pt, Mm
import time
import numpy as np
import pyodbc
import datetime
import pandas as pd
import runpy
import codecs
import collections
from multiprocessing import Process, Queue
import threading
from datetime import timedelta
import warnings
from win32com import client
from datetime import datetime
import os
import time
import glob
import time
import time
from datetime import datetime, timezone, timedelta
warnings.filterwarnings("ignore")
kronos_df = pd.read_excel(r"\\teslamotors.com\us\Public\stalamakki\ExcelFiles\KronosDataHourlyRefresh.xls")
kronos_df.fillna('')
clockRecords = kronos_df.to_dict('records')
sqlUpsert = """
INSERT INTO "daily_performance_metrics"."employee_kronos_data_2"
VALUES (%s,%s,%s,%s,%s)
"""
# VALUES (%s,to_timestamp(%s, 'YY-MM-DD HH24:MI'),COALESCE(to_timestamp(NULLIF(%s, '01/01/01 00:00'),'MM/DD/YY hh24:mi')),%s,%s)
#sqlDelete = """
# DELETE FROM "daily_performance_metrics"."employee_kronos_data" WHERE CustomerName='Alfreds Futterkiste';
postgres_conn = psycopg2.connect("host=sjc04p1scadb02.teslamotors.com dbname=service_warehouse_metrics user=service_warehouse_rw port=5432 password=gvjY96LcnWn2B3+obVjFsLG5erMy/4JNxgN00Lnq2n0=")
postgres_cursor = postgres_conn.cursor()
for record in clockRecords:
if record['ShiftEnd'] == '':
record['ShiftEnd'] = None
if record['ShiftStart'] == '':
record['ShiftStart'] = None
postgres_cursor.execute(sqlUpsert,list(record.values()))
postgres_conn.commit()
postgres_cursor.close()
postgres_conn.close()
...generates this error message when it tries to write what I assume is the first record with a null value...
---------------------------------------------------------------------------
DatatypeMismatch Traceback (most recent call last)
<ipython-input-73-2ef7c8c3820c> in <module>()
15 if record['ShiftStart'] == 'NaN':
16 record['ShiftStart'] = None
---> 17 postgres_cursor.execute(sqlUpsert,list(record.values()))
18 postgres_conn.commit()
19 postgres_cursor.close()
DatatypeMismatch: column "shift_end" is of type timestamp without time zone but expression is of type double precision
LINE 3: ... VALUES ('zvolkert','10/02/19 13:13','NaN'::flo...
^
HINT: You will need to rewrite or cast the expression.
To deal with the Nulls, I've tried this syntax for the INSERT statement...
INSERT INTO "daily_performance_metrics"."employee_kronos_data_2"
VALUES (%s,to_timestamp(%s, 'YY-MM-DD HH24:MI'),COALESCE(to_timestamp(NULLIF(%s, '01/01/01 00:00'),'MM/DD/YY hh24:mi')),%s,%s)
...which generates this error message...
InvalidTextRepresentation: invalid input syntax for type double precision: "01/01/01 00:00"
LINE 3: ...4:MI'),COALESCE(to_timestamp(NULLIF('NaN'::float, '01/01/01 ...
I'm assuming this is a very simple syntax mistake. Would really appreciate if someone could tell me the correct syntax for getting these strings and null values into the timestamp fields.
I'm writing to this table...
CREATE TABLE daily_performance_metrics.employee_kronos_data_5 (
file_number TEXT
,shift_start TIMESTAMP
,shift_end TIMESTAMP
,job_category TEXT
,job_name TEXT
)
Here's the file that i'm trying to copy to the database:
ClockInOutRecords.xlsx
Solution was simply to replace the nan values with none. I thought I was already doing that but the == 'NaN' syntax was incorrect. The correct syntax for checking for NaN is pd.isna. Fixed code below...
sqlUpsert = """
INSERT INTO "daily_performance_metrics"."employee_kronos_data_2"
VALUES (%s,COALESCE(to_timestamp(%s, 'MM/DD/YY hh24:mi')),COALESCE(to_timestamp(%s, 'MM/DD/YY hh24:mi')),%s,%s)
"""
# VALUES (%s,%s,%s,%s,%s)
# VALUES (%s,to_timestamp(%s, 'YY-MM-DD HH24:MI'),COALESCE(to_timestamp(NULLIF(%s, '01/01/01 00:00'),'MM/DD/YY hh24:mi')),%s,%s)
postgres_conn = psycopg2.connect("host=sjc04p1scadb02.teslamotors.com dbname=service_warehouse_metrics user=service_warehouse_rw port=5432 password=gvjY96LcnWn2B3+obVjFsLG5erMy/4JNxgN00Lnq2n0=")
postgres_cursor = postgres_conn.cursor()
postgres_cursor.execute(sqlDelete)
for record in clockRecords:
# print(list(record.values()))
if pd.isna(record['ShiftEnd']):
# print(record['ShiftEnd'])
record['ShiftEnd'] = None
# print(record['ShiftEnd'])
if pd.isna(record['Job_Category']):
record['Job_Category'] = None
if pd.isna(record['Job_Name']):
record['Job_Name'] = None
# print(list(record.values()))
postgres_cursor.execute(sqlUpsert,list(record.values()))
# print('success')

Datetime and Time can't be used in the same program?

So I'm writing a program with
import datetime
import time
I'm using time to record the time it takes the program to run, and I need to check the date so if the file is more than a certain age, don't process it.
I keep getting this error when trying to use these two classes
Traceback (most recent call last):
File "<stdin>", line 563, in <module>
File "<stdin>", line 498, in main
AttributeError: type object 'datetime.time' has no attribute 'time'
shell returned 1
Is it not possible to use both time and datetime in one program?
Some of the code:
import PyPDF2
import re
import os
#Time testing
import time
#Using this to check if address is in proper format and to clean it up
import usaddress
#testing this one out
import datetime
from dateutil.parser import *
from dateutil.tz import *
from datetime import *
#Timer starts
start_time = time.time() #Error is referring to this line, line 498
#Opens 3 different files
#For file in folder parse it to text
#Writes some things to file
#Gets the date from the file
if date != None:
fileDate = parse(date).year
now = datetime.now()
print now.year, now.month, now.day
#Ends the timer and prints the time to the console
print("--- %s seconds ---" % round(time.time() - start_time, 2))
Here is your problem:
import datetime
from dateutil.parser import *
from dateutil.tz import *
from datetime import * # <<<< problems
First you are importing datetime and then you are importing everything from datetime.
Be explicit, and only import what you need.
from datetime import datetime
Then you can use it as datetime.now or whatever methods you may need.
As a rule of thumb, never import *. It causes exactly these sorts of issues.
The problems is:
from datetime import *
because it imports time from datetime. It's always better to import only what you need. But if you also really need this method you could do (for example):
from datetime import time as dt
That's why import * is dangerous...

AttributeError: 'list' object has no attribute 'astimezone'

My python script:
import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob
def ftphttp():
files = glob.glob('Desktop/images/*.png')
ts = map(os.path.getmtime, files)
dts = map(datetime.fromtimestamp, ts)
print ts
timeZone= timezone('Asia/Singapore')
#converting the timestamp in ISOdatetime format
localtime = dts.astimezone(timeZone).isoformat()
I was trying to get the multiple files timestamp. I able to print out all the files in my folder
[1467910949.379998, 1466578005.0, 1466528946.0]
But it also prompt me this error about the timezone. Anybody got any ideas?
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
ftphttp()
File "/home/kevin403/Testtimeloop.py", line 22, in ftphttp
localtime = dts.astimezone(timeZone).isoformat()
AttributeError: 'list' object has no attribute 'astimezone'
You are trying to call a method on a list of objects, instead of the objects in the list. Try calling the method on the first object instead:
localtime = dts[0].astimezone(timeZone).isoformat()
Or map over the list to get all timestamps in iso format:
localtimes = map(lambda x: x.astimezone(timeZone).isoformat(), dts)
dts is a list of time zones. So you need to do:
[ts.astimezone(timeZone) for ts in dts]
This will give you a list of the three time zones

Categories

Resources