Python - defining global name datetime - python

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.).

Related

Create and initialise a time column Python

I need to add a time column to my existing dataframe and initialize it. I tried this line of code df['date']=datetime.time(0, 0, 0) in a small script :
import pandas as pd
import datetime
df = pd.DataFrame({'column1':[34,54,32,23,26]})
df['date']=datetime.time(0, 0, 0)
print(df['date'])
output:
0 00:00:00
1 00:00:00
2 00:00:00
3 00:00:00
4 00:00:00
but when I implemented it in my code, in which I work on large dataframes, I got this error:
dfreez['delta']=datetime.time(0, 0, 0)
TypeError: descriptor 'time' for 'datetime.datetime' objects doesn't apply to 'int' object
this is a piece of my code:
import pandas as pd
dfreez = pd.read_excel('file_name.xlsx',header=0, index= False)
from datetime import datetime
dfreez['delta']=datetime.time(0, 0, 0)
I don't understand what went wrong!
import datetime and from datetime import datetime and not the same.
After the first one, the local datetime variable is a reference to the module. So you can access the datetime class with datetime.datetime and the time class with datetime.time
After the second, the local datetime variable is a reference to the datetime class. So you have no (direct *) way to access the time class.
You should just use:
import datetime
in the second snippet just like what was done in first one.
(*) FYI: it is still possible with the ugly sys.modules['datetime'].time. But never pretend that I advised you to do that!

datetime.datetime has no attribute "datetime"

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.

'datetime.datetime' object has no attribute 'read'

Users in my app have date_joined fields that are in this format: 2014-12-14 14:46:43.379518+00:00
In order to pass this datetime along to Intercom.io, it must be a UNIX timestamp like this: 1426020706 (this is not the same time, just an example).
I've tried several methods I've read here on Stack Overflow (nothing in this question has the same starting time format: Converting datetime.date to UTC timestamp in Python), but none have worked. mktime() seemed promising, but I got "'datetime.datetime' object has no attribute 'mktime'."
I just tried this:
import time
import dateutil.parser
import member.models import Member
member = Member.objects.get(email="aspeksnijder#outlook.com")
date_joined = member.date_joined
dt = dateutil.parser.parse(date_joined)
print int(time.mktime(dt.timetuple()))
It returned "'datetime.datetime' object has no attribute 'read'". How can I accomplish this?
It seems you have an aware datetime object. If you print it then it looks like:
2014-12-14 14:46:43.379518+00:00
To be sure print(repr(date_joined)).
Converting datetime.date to UTC timestamp in Python shows several ways how you could get the timestamp e.g.,
timestamp = date_joined.timestamp() # in Python 3.3+
Or on older Python versions:
from datetime import datetime
# local time = utc time + utc offset
utc_naive = date_joined.replace(tzinfo=None) - date_joined.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
Note: timestamp = calendar.timegm(date_joined.utctimetuple()) would also work in your case but it may return a wrong result silently if you pass it a naive datetime object that represents local time by mistake.
If your input is a time string then convert the time string into a datetime object first.
What about (using the dateutil and pytz packages):
import dateutil.parser
from datetime import datetime
import calendar
import pytz
def str2ts(s):
''' Turns a string into a non-naive datetime object, then get the timestamp '''
# However you get from your string to datetime.datetime object
dt = dateutil.parser.parse(s) # String to non-naive datetime
dt = pytz.utc.normalize(dt) # Normalize datetime to UTC
ts = calendar.timegm(dt.timetuple()) # Convert UTC datetime to UTC timestamp
return int(ts)
def ts2str(ts):
'''Convert a UTC timestamp into a UTC datetime, then format it to a string'''
dt = datetime.utcfromtimestamp(ts) # Convert a UTC timestamp to a naive datetime object
dt = dt.replace(tzinfo=pytz.utc) # Convert naive datetime to non-naive
return dt.strftime('%Y-%m-%d %H:%M:%S.%f%z')
Which we can test with:
# A list of strings corresponding to the same time, with different timezone offsets
ss = [
'2014-12-14 14:46:43.379518+00:00',
'2014-12-14 15:46:43.379518+01:00',
'2014-12-14 16:46:43.379518+02:00',
'2014-12-14 17:46:43.379518+03:00',
]
for s in ss:
ts = str2ts(s)
s2 = ts2str(ts)
print ts, s2
Output:
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
These output all the same timestamps, and "verification" formatted strings.
You can try the following Python 3 code:
import time, datetime
print(time.mktime(datetime.datetime.strptime("2014-12-14 14:46:43.379518", '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc).timetuple()))
which prints:
1418568403.0
I had that problem when I used input from Django's DateField, which is displayed in a form of XXXX-YY-ZZ: parse(django_datefield) causes the exception.
The solution: use str(django_datefield).
parse(str(django_datefield))
I know this is an old post, but I want to highlight that the answer is likely what #Peter said in his comment:
It looks like member.date_joined is already a datetime object, and there's no need to parse it. – Peter Feb 25 '17 at 0:33
So-- your model probably already parses into a datetime.datetime object for you.

How check if current date and time is after a given date and time

In Python:
How check if current date and time is after a given date and time object named "next_check"
Add X number of minutes to next check
You can do both of those things with datetime (assuming you import datetime and next_check is actually a datetime.datetime instance):
if datetime.datetime.now() > next_check; and
next_check += datetime.timedelta(minutes=X).
If it isn't a datetime.datetime instance, that module contains various functions (e.g. strptime) to make it into one.

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