datetime.datetime has no attribute "datetime" - python

I'm trying to determine if the current time is before or after a specified date using this code:
from datetime import datetime
def presidentvoting(self):
electiondate = datetime.datetime(2020, 1, 31, 0, 0)
current_time = datetime.now()
if current_time > electiondate:
print("You can no longer vote")
But I'm getting this error:
electiondate = datetime.datetime(2020, 1, 31, 0, 0)
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
What am I doing wrong?

datetime is a module which contains a function1 that is also called datetime.
You can use it like this:
import datetime
# ^^^^^^^^
# the module
x = datetime.datetime(...)
# ^^^^^^^^ the function
# ^^^^^^^^ the module
Here datetime refers to the module, and datetime.datetime refers to the function in the module.
Or you can only import the function from the module, like this:
from datetime import datetime
# ^^^^^^^^ ^^^^^^^^
# the module the function
x = datetime(...)
# ^^^^^^^^ the function
You used a mixture of those two, which does not work:
from datetime import datetime
# ^^^^^^^^ ^^^^^^^^
# the module the function
x = datetime.datetime(...)
# ^^^^^^^^ this does not exist
# ^^^^^^^^ the function
In case use used
import datetime
from datetime import datetime
then after the first line, datetime would refer to the module (which on its own would have been correct), but the second line would overwrite that and datetime would no longer refer to the module, but to the function.
1 Actually, datetime.datetime is a class, not a function, but for the purpose of this answer it does not matter.

Related

How to Convert "2021-08-17T20:03:36.480-07:00" to local time in Python?

So, "2021-08-17T20:03:36.480-07:00", is given as as a string. I want to convert it into the local time.
Something like this 2020-01-06 00:00:00.
This is what I had tried earlier
from datetime import datetime
def convert_utc_local(utc_time):
conv_time = ' '.join(utc_time.split("T"))
return conv_time.astimezone(tzlocal())
And the error came to
return utc_time.astimezone(tzlocal())
AttributeError: 'str' object has no attribute 'astimezone'"
So what worked for me was this:
def convert_utc_local(utc_time):
to_zone = tz.gettz('Asia/Tokyo')
iso_to_local = datetime.fromisoformat(utc_time).astimezone(to_zone)
dt = str(iso_to_local.replace(tzinfo=None).isoformat(' ', timespec='seconds'))
return dt
Make use of datetime.fromisoformat. It gives clean code and is efficient. There's also the "inverse" method available, datetime.isoformat, which returns a string from a datetime object.
Converter can be written as a one-liner:
from datetime import datetime
# iso_to_localdt converts an ISO8601 date/time string to datetime object,
# representing local time (OS setting).
iso_to_localdt = lambda t: datetime.fromisoformat(t).astimezone(None)
In use:
dt = iso_to_localdt("2021-08-17T20:03:36.480-07:00")
print(repr(dt))
# datetime.datetime(2021, 8, 18, 5, 3, 36, 480000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'Mitteleuropäische Sommerzeit'))
print(dt.isoformat(' ', timespec='seconds'))
# 2021-08-18 05:03:36+02:00
# to get local time without the UTC offset specified, i.e. naive datetime:
print(str(dt.replace(tzinfo=None).isoformat(' ', timespec='seconds')))
# 2021-08-18 05:03:36
Note: your time zone might be different.
Before you change timezone you need to convert conv_time to datetime object with strptime. Then, to change the format you simply use strftime.
For example:
from datetime import datetime
from dateutil import tz
def convert_utc_local(utc_time):
time = datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%S.%f%z')
# Convert time zone
local_time = time.astimezone(tz.tzlocal())
return local_time.strftime('%Y-%m-%d %H:%M')
print(convert_utc_local("2021-08-17T20:03:36.480-07:00"))

I need date for the file I created in the format "yyyy-mm-dd", but I don't understand what datetime.datetime.timstamp() returns

The code I've written so far is included below. I am under the
impression that assigning a variable to
datetime.datetime.fromtimestamp() will result in a list, so I created
my Python code like below. I want my function to return the time
that I first created my file as a substring of a string in the format
"yyyy-mm-dd". I would greatly appreciate any help in making this code work correctly.
import os
import datetime
def file_date(filename):
# Create the file in the current directory
with open(filename, "x") as file1:
pass
timestamp = os.path.getmtime(file1)
# Convert the timestamp into a readable format, then into a string
list1 = datetime.datetime.fromtimestamp(timestamp)
str1 = "-".join(list1)
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return ("{str1[0:9]}".format(str1)
print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd
list1 is an object of type datetime.datetime to format it as a string use
time_in_string = list1.strftime('%Y-%m-%d')
No. datetime.datetime.fromtimestamp is a named constructor (a constructor "constructs" instances of a class) for datetime instances (object of the datetime class). This means that calling datetime.datetime.fromtimestamp(timestamp) will give you a datetime object corresponding to that timestamp and not a list. When you print the datetime instance you get datetime.datetime(2021, 1, 13, 13, 15, 1, 270342).
To parse the datetime instance as a formatted time string "yyyy-mm-dd", you can use
list1.strftime("%Y-%m-%d")
where %Y is the year %m is the zero padded month and %d is the zero padded day
You can also use a try this function -
>>> import os
>>> import platform
>>> from datetime import datetime
>>>
>>> def file_creation(path_to_file):
... if platform.system() == 'Windows':
... dt = os.path.getctime(path_to_file)
... else:
... stat = os.stat(path_to_file)
... try:
... dt = stat.st_birthtime
... except AttributeError:
... dt = stat.st_mtime
... return datetime.fromtimestamp(dt).strftime("%Y-%m-%d")
...
>>>
>>> file_creation('test.sh')
'2018-06-18'
getmtime and getctime takes path instead of the file object
type of (datetime.fromtimestamp(timestamp)) is 'datetime.datetime', not a list
import os
import time
from datetime import datetime
def file_date(filename):
with open(filename, 'w') as file1:
pass
path = os.path.abspath(filename)
timestamp = os.path.getctime(path)
date_created = datetime.fromtimestamp(timestamp)
str_DT = date_created.strftime('%Y-%m-%d')
return str_DT
print(file_date("file2.txt"))

Python: Change the format of python object date-time to string and change it back to python object to be comparable with other date?

I have a code in which I have two dates inputs (in different formats) and I want them to be the same format (date-time python object) and so I will be able to compare these two days. One of them is a string and the other is a python object:
import pythonwhois
import datetime
from datetime import date
from dateutil.parser import parse
from datetime import datetime
bl_time = l.split('\t')
bl_time = bl_time.strip('\n')
bl_date = datetime.datetime.strptime(bl_time ,"%b %d %Y").strftime('%d/%m/%Y')
date1 = datetime.strptime(bl_date,'%d/%m/%Y')
w = pythonwhois.get_whois(domain)
date2 = (w['creation_date'])[0].strftime(bl_date, '%d/%m/%Y').strptime(bl_date,'%d/%m/%Y')
and i am receiving this error:
Traceback (most recent call last):
File "/Users/Documents/scripts/whois.py", line 29, in <module>
bl = datetime.datetime.strptime(bl_time ,"%b %d %Y").strftime('%d/%m/%Y')
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
can anybody help?
Since you did from datetime import datetime, in your code, datetime is the class, not the module. Change
datetime.datetime.strptime(bl_time, ...).strftime(...)`
to
datetime.strptime(bl_time, ...).strftime(...)`
and you should be all set1.
1at least as far as this error is concerned... ;-)

Python - defining global name datetime

I'm trying to create a function where I use various functions from the datetime module, such as strftime, strptime and timedelta.
I feel like I've tried everything, but every time I am told this:
4 date = '2012.09.07'
5
----> 6 q = net(date)
7 print q
/Users/fb/Documents/Python_files/test_function.pyc in net(date)
1 def net(date):
----> 2 b = datetime.strptime(a, '%Y.%m.%d')
3 c = b.strftime('%d:%m:%y')
4 return c
NameError: global name 'datetime' is not defined
I've read that others probably experience the same problem as I, namely ' It works in the python interpreter but not in the script'. Can anyone help, please?
You need to import the datetime object in your module:
from datetime import datetime
at the top of test_function.py.
In your interpreter session you probably already imported the object.
Your whole module will then look like:
from datetime import datetime
def net(date):
b = datetime.strptime(date, '%Y.%m.%d')
c = b.strftime('%d:%m:%y')
return c
where I replaced a with date, since that is the name of the actual argument to the function.
Note that the datetime module contains a datetime class, which is the only thing imported here. If you need access to the date and timedelta classes as well, import these explicitly (from datetime import datetime, date, timedelta) or import just the module and refer to the contents as attributes (import datetime, then datetime.datetime.strptime() and datetime.date.today(), etc.).

type object 'datetime.datetime' has no attribute 'datetime'

I have gotten the following error:
type object 'datetime.datetime' has no attribute 'datetime'
On the following line:
date = datetime.datetime(int(year), int(month), 1)
Does anybody know the reason for the error?
I imported datetime with from datetime import datetime if that helps
Thanks
Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.
Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.
>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
But, if you import datetime.datetime:
>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work
# as you imported the type, not the module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
I suspect you or one of the modules you're using has imported like this:
from datetime import datetime.
For python 3.3
from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)
You should really import the module into its own alias.
import datetime as dt
my_datetime = dt.datetime(year, month, day)
The above has the following benefits over the other solutions:
Calling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).
The module and the class (both called datetime) do not shadow each other.
You should use
date = datetime(int(year), int(month), 1)
Or change
from datetime import datetime
to
import datetime
If you have used:
from datetime import datetime
Then simply write the code as:
date = datetime(int(year), int(month), 1)
But if you have used:
import datetime
then only you can write:
date = datetime.datetime(int(2005), int(5), 1)
I run into the same error maybe you have already imported the module by using only import datetime so change from datetime import datetime to only import datetime. It worked for me after I changed it back.
import time
import datetime
from datetime import date,timedelta
You must have imported datetime from datetime.
I found this to be a lot easier
from dateutil import relativedelta
relativedelta.relativedelta(end_time,start_time).seconds
Avoid to write:
from datetime import datetime
datetime.datetime.function()
Solution No. 1:
import datetime
datetime.datetime.function()
Solution No. 2:
from datetime import datetime
datetime.function()
from datetime import datetime
import time
from calendar import timegm
d = datetime.utcnow()
d = d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
utc_time = time.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)
delete one datetime from:
date = datetime.datetime(int(year), int(month), 1)
and you get this:
date = datetime(int(year), int(month), 1)
you already imported the first one with this:
from datetime import datetime
so its redundant.
The Problem Is That You Are Using The Tag
from datetime
I had The Same Problem You Need To use It Like This Instead
import datetime

Categories

Resources