Python 3 - datetime Class/module Error in VS Code (Windows) - python-3.x

I am trying to print a simple statement that will show today's date. But no matter how I try, I keep getting the same error. Here are some examples:
import datetime
today = datetime.datetime.date.today()
print(today)
I've also tried:
from datetime import datetime
today = datetime.date.today()
print(today)
Either way, this is the error message I get in the terminal:
"AttributeError: partially initialized module 'datetime' has no attribute 'date' (most likely due to a circular import)"
Any advice? I'm going nuts and yet, it should be so simple! #_#

Your file name is the same as the package:
Change it for antoher name, like 'Time_example.py'

Related

Quantstats - TypeError: Invalid comparison between dtype=datetime64[ns, America/New_York] and datetime

I'm trying to use some of the Quantstats modules, specifically the quantstats.reports module, in Anaconda to get some metrics reports on a portfolio I've designed. I'm fairly new to Python/Quantstats and am really just trying to get a feel for the library.
I've written the following code to utilize the report module to spit out a complete html report and save it under the Output folder:
import quantstats as qs
qs.extend_pandas()
stock = qs.utils.download_returns('GLD')
qs.reports.html(stock, output='Output/GLD.html')
I then get the following TypeError:
TypeError: Invalid comparison between dtype=datetime64[ns, America/New_York] and datetime
I believe this may be a result of the datetime64 class being localized to my timezone and datetime remaining TZ naive. Frankly, digging through the Quantstats code has been a little beyond my current skillset.
If anybody has any recommendations for fixes, I would greatly appreciate it.
I came upon this while DDGing exactly the same issue.
Not sure which of your columns has the timezone localisation in it, but
df['date'] = df['date'].dt.tz_localize(None)
will get rid of localization for the column df['date']
Incidentally, the usual situation is that the index of a pandas timeseries contains np.Datetime64 types, but when you assign it to a column via
df['date'] = df.index
the resulting column contains pandas Timestamps.
I got this issue resolved after I had lowered the yfinance version from latest version 0.1.87 to
yfinance => 0.1.74

How to supress warning: Datetime with no tzinfo will be considered UTC?

I have the following code which am using to monitor Azure ADF pipeline runs. The code uses 'RunFilterParameters' to apply a date range filter in extracting run results:
filter_params = RunFilterParameters(last_updated_after=datetime.now() - timedelta(1), last_updated_before=datetime.now() + timedelta(1))
query_response = adf_client.activity_runs.query_by_pipeline_run(resource_group, adf_name, row.latest_runid,filter_params)
The above works ok, however it is throwing a warning:
Datetime with no tzinfo will be considered UTC
Not sure how to add timezone to this or just suppress the warning?
Please help.
"no tzinfo" means that naive datetime is used, i.e. datetime with no defined time zone. Since Python assumes local time by default for naive datetime, this can cause unexpected behavior.
In the code example given in the question, you can create an aware datetime object (with tz specified to be UTC) like
from datetime import datetime, timezone
# and use
datetime.now(timezone.utc)
If you need to use another time zone than UTC, have a look at zoneinfo (Python 3.9+ standard library).

Changing datetime format in py

I have the following code which gives the following output:
print(df1['Diff'].mean())
outputs:
10 days 16:13:29.467455
But since i just want the days value and not the time, i have done this:
print(datetime.strptime(df1['Diff'].mean(), format ='%d')
but i am getting the following error:
^
SyntaxError: unexpected EOF while parsing
Why am i getting this error?
For date, time, and datetime objects
You should be using strftime to format the time, not to parse the time (as in strptime).
print(obj.strftime('%d'))
strptime expects a string to be passed in (and you were passing in a datetime object), whereas strftime formats an existing datetime object.
For timedelta objects
print(obj.days)
This gets the days counterpart you're looking for.
I think the instance of df1['Diff'].mean() is str and datetime.strptime() can be use only in datetime methods. So to only get date you have to take slice of df1['Diff'].mean() like df1['Diff'].mean()[:-14]
Which is in your case.

Catching Import errors and Name errors in Python during "compile" time

Can you catch import / name and other errors in python using a (linting) tool or a compilation step?
The other option is to make sure all possible code paths are tested (This is not always feasible, especially for large existing code bases and other reasons)
Here are some examples.
Missing import - caught by pylint, although as a syntax error instead of an import error.
def test():
print("Time now is ..", datetime.datetime())
pylint output:
E0602: Undefined variable 'datetime' (undefined-variable)
Import present, but incorrect method used. This passes both pylint and py_compile.
from datetime import datetime
def test():
print("Time now is ..", datetime.today2())
Edit: To add one more option.
Doing an import * shows some errors, but not errors in statements which are inside the functions.
This error is reported
from datetime import datetime
print("today2", datetime.today2())
Error :
Python 3.7.0 (default, Aug 22 2018, 15:22:56)
>>> from test import *
...
print("today2", datetime.today2())
AttributeError: type object 'datetime.datetime' has no attribute 'today2'
>>>
This is not.
from datetime import datetime
def test():
print("Time now is ..", datetime.today2())
In my experience, flake8 does a great job of catching missing imports and name errors. In order to catch missing imports, you must not use wildcard imports like "from foo import *", since it cannot guess which names that will create. Also, it cannot do these detections while syntax errors exist, so you have to fix those first.
Unlike c++ which is a compiled language, python is an interpreted language. Which means it doesn't have compile phase. It interpreted code line by line.
According to that, you didn't find the errors until you reach them in runtime.
If you want that errors appears, you should somehow path throw every line of your code. The best approach is using test libraries with 100% test coverage.
For more information look at this question and it's answers.

datetime Attribute error in python

I'm trying to run to following three lines of python code on command line using Python 3.5.0. It gives me an error- Attribute error: module 'datetime' has no attribute 'date'. I just want to print current date. Please help.
import datetime
current = datetime.date.today()
print(current)
There is nothing wrong with your code. It could be reduced a bit though:
import datetime
datetime.date
which should also cause the error. If this really causes the error, I would say your installation is messed up or, unlikely, there's a bug in Python. Please also make sure you don't have a datetime.py in your working directory. Further, check the output of dir(datetime) after importing it and with a different version of Python.
You shouldn't be getting any error running the above code as there is nothing wrong with it. Also rather than using the above code (which is okay syntax-wise but imports all the names accessible in the datetime moudule), you could use
from datetime import date
current = date.today()
print(current)
since all you want to import is the day's date.
when i run it on python 27. the code returns date with no errors!

Resources