AttributeError: 'datetime' module has no attribute 'strptime' - python

Here is my Transaction class:
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
And when I'm trying to run the date function:
tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date
I'm getting the following error:
self.date = datetime.strptime(self.d, "%Y-%m-%d")
AttributeError: 'module' object has no attribute 'strptime'
How can I fix that?

If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime module also named their class datetime:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime: that's the module (that's what you have right now).
from datetime import datetime: that's the class.

I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with
the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.

Values ​​may differ depending on usage.
import datetime
date = datetime.datetime.now()
date.strftime('%Y-%m-%d') # date variable type is datetime
The value of the date variable must be a string::
date = '2021-09-06'
datetime.datetime.strptime(date, "%Y-%m-%d")
str(datetime.datetime.strptime(date, "%Y-%m-%d")) # show differently

The solutions mentioned by the others are correct. But for me, it was a problem with another library importing datetime module for me and overriding the datetime class I was importing.
an example with tsai library:
from datetime import datetime
from tsai.all import *
This will give you the error: 'module' object has no attribute 'strptime'.
In this case, just flip the order of imports or just don't import everything (even if the documentation does that) :
from tsai.all import *
from datetime import datetime

Related

The zone attribute is specific to pytz's interface; please migrate to a new time zone provider

I need to filter the lines where the date is today and not more than 2 hours ago according to local time (the code needs to be malleable as I travel to different timezones):
from tzlocal import get_localzone
import pandas as pd
import pytz
df['DATA_HORA'] = df.apply(lambda x: datetime.strptime(f'{x["DATA"]} {x["HORA"]}', '%d/%m/%Y %H:%M'), axis=1)
local_tz = get_localzone()
local_tz = pytz.timezone(local_tz.zone)
df_today = df[(df['DATA_HORA'].dt.tz_localize(local_tz) >= (datetime.now(local_tz) - timedelta(hours=2))) & (df['DATA_HORA'].dt.date == datetime.now(local_tz).date())]
I tried to understand how to do it, according to the specific documentation about it:
https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html#getting-a-time-zone-s-name
But I was not successful, how should I proceed to find my local timezone and not receive this warning anymore?
tzlocal.get_localzonealready returns a timezone object, which you can use directly:
import pandas as pd
from tzlocal import get_localzone
z = get_localzone()
print(repr(z))
# _PytzShimTimezone(zoneinfo.ZoneInfo(key='Europe/Berlin'), 'Europe/Berlin')
print(pd.Timestamp("now", tz=z))
# 2023-02-14 17:54:32.445179+01:00
You can also unwrap it and obtain the string representation in a way that doesn't trigger warnings:
print(repr(z.unwrap_shim()))
# zoneinfo.ZoneInfo(key='Europe/Berlin')
print(z.unwrap_shim().key)
# Europe/Berlin
...or also like
from tzlocal import get_localzone_name
print(get_localzone_name())
# Europe/Berlin
Note that if you use pandas, you neither need the datetime module nor pytz here.

Timezone getting removed in python flask

After a user logs in, I am setting a session variable to the time with utc.. but the timezone is getting stripped.
import datetime
from pytz import timezone
utc = timezone('utc')
session['login_time'] = datetime.datetime.now(utc)
When I print after the assignment the timezone is there 2021-06-11 23:56:00.161971+00:00. And a decorator function gets called. When I print session['login_time'] the timezone is removed. 2021-06-11 23:56:00
For me, I will use .strftime to help format the datetime and %Z is to show the timezone.
You can see the strftime document to help you format the time. I will use this code to replace your original one:
session['login_time'] = datetime.datetime.now(utc).strftime('"%Y-%m-%d %H:%M:%S%Z"')
login_time = datetime.datetime.strptime(session['login_time'],"%Y-%m-%d %H:%M:%S%Z" )
utct = utc.localize(login_time)
print(utct)
print(type(utct))
And here is the output:
2021-06-12 01:00:23+00:00
<class 'datetime.datetime'>
I had to re-add the timezone('utc') when i needed to use the time in another function.
def diff_min(t):
utc = timezone('utc')
t = utc.localize(t)

Convert datetime to protobuf Timestamp in Python

So I'm trying to prepare a message with Python that takes a Timestamp, but I'm having trouble converting a datetime to a protobuf Timestamp.
Here's what I've tried so far:
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
However, I'm getting an error AttributeError: 'Timestamp' object attribute 'seconds' is read-only
How can I create a Timestamp from a datetime?
This code is working fine on my machine
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
Output:
seconds: 1591859232
nanos: 803377000

Datetime 'has no attribute now'

I'm trying to write a simple program to print the current date with Python 3.4. In the shell, I can import datetime, and use now() but when I write a script with a class it fails and gives this error:
"AttributeError: module object has no attribute now".
Can anyone help explain the problem? This is my code:
import datetime
class Date:
def __init__(self, filename):
self.writeToFile(filename)
def date(self):
now = datetime.datetime.now()
return now
def writeToFile(self, filename):
date = self.date()
file = open(filename, 'w')
file.write(date)
for i in range(20): # simply test for writting in file
file.write(str(i)+'\t')
file.close()
return file
d = Date('datetime.txt')
import datetime
datetime.datetime.now()
Make sure you are importing the intended datetime module, and it is not being overridden by local files with same name. you can check it with:
import datetime
print(datetime.__file__)
and check the output if it is pointing to the correct directory you want.
I had this error too and all I did was
Import datetime
from datetime import datetime
# then u can declare ur variable let's say something like
today = datetime.datetime.now()
#u can add what ever u want
#the point is make sure u do the datetime.datetime.now()
print(today)

How do you add datetime to a logfile name?

When I create my logfile, I want the name to contain the datetime.
In Python you can get the current datetime as:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 2, 3, 21, 35, 9, 559000)
The str version is
>>> str(datetime.now())
'2012-02-03 21:35:22.247000'
Not a very nice str to append to the logfile name! I would like my logfile to be something like:
mylogfile_21_35_03_02_2012.log
Is there something Python can do to make this easy? I am creating the log file as:
fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")
You need datetime.strftime(), this allows you to format the timestamp using all of the directives of C's strftime(). In your specific case:
>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log')
'mylogfile_08_48_04_02_2012.log'
You could also use a TimedRotatingFileHandler that will handle the date and the rollover every day (or whenever you want) for you.
from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile', when='midnight')
By default the format will be depending on the rollover interval:
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.
But you can modify that as showed here, by doing something like:
from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile', when='midnight')
fh.suffix = '%Y_%m_%d.log'
Yes. Have a look at the datetime API, in particular strftime.
from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
Another Solution using format():
#generates a date for a generic filename
import datetime
date_raw = datetime.datetime.now()
date_processed = "{}-{}-{}_{}-{}-{}".format(date_raw.year, date_raw.month,
date_raw.day, date_raw.hour, date_raw.minute, date_raw.second)
#example value: date_processed = 2020-1-7_17-17-48
I used this in my own project
edit: as I found out about f(ormatted)-strings, this would be another solution:
date_processed = f"{date_raw.year}-{date_raw.month}-{date_raw.day}_{date_raw.hour}-{date_raw.minute}-{date_raw.second}"
We can use datetime.now() to get current timestamp. Here is my code that I am using to create log file with timestamp -
import logging
from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')
from time import strftime
fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
To print hour, minutes, day, month and year, use the following statement
from datetime import datetime
print datetime.now().strftime("%H_%M_%d_%m_%Y")

Categories