How to turn the value of a variable into a datetime object - python

I have an input in tkinter where a date is entered in the format of dd/mm/yyyy . I would like to make a variable equal to the three letter version of the month and another to be equal to the yyyy of a month.
the input variable is date_entry and I've tried
ss_date = date_entry.strftime("%d/%m/%Y")
and
ss_date = (datetime.strptime(date_entry, "%d/%m%Y"))
but i keep getting module 'datetime' has no attribute 'strptime'
I've looked online but every example uses datetime to generate an example in the first place, I cannot find any explanation of how to extract it from a variable value.
```
ss_date = date_entry.strftime("%d/%m/%Y") and
ss_date = (datetime.strptime(date_entry, "%d/%m%Y"))
```
module 'datetime' has no attribute 'strptime'
Can you please help.

Please make sure you import datetime correctly. Python has a library datetime which then also has a datetime object in it. So either import the object version directly, or call it by the 'full name' (datetime.datetime).
Object version:
from datetime import datetime
date_entry = "04/05/2019"
datetime.strptime(date_entry, "%d/%m/%Y")
'Full name' version:
import datetime
date_entry = "04/05/2019"
datetime.datetime.strptime(date_entry, "%d/%m/%Y")

Related

is there any solution for Datetime error in python?

I need help in my code as I'm new in python. I'm using the DateTime library in my code to know the current datetime and doy1 for finding the day of the year.
I tried using python 3.6 idle with different modules and after that, I used Visual Studio community 2017(just for my satisfaction) but it showing me an error. I know it's not tool issue but I just tried.
import datetime
from dateutil import parser
from datetime import datetime
ask=input("enter date\n")
date_format = "%Y-%m-%d"
date_time = datetime.strptime(ask, date_format)
Current_date = datetime.strptime((str(datetime.now().date())), date_format)
print(Current_date)
doy1=date_time.strftime("%j")# day of year
date=datetime.now()
doy2=date.strftime("%j")
if(doy1<doy2):
diff_of_dates=abs(int(doy1)-int(doy2))
print(diff_of_dates)
diff=diff_of_dates+1
for i in range(1,diff):
avg_20=int(doy1)+1
print(doy1)
temp_date=datetime.date(date_format)+datetime.timedelta(doy1-1)
print("Difference of day",temp_date)
#ERROR
Traceback (most recent call last):
File "C:\Users\Muahr\source\repos\RCAI-Project\Pest\temperature.py", line 157, in <module>
temp_date=datetime.date(date_format)+datetime.timedelta(doy1-1)
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'str'
I think I solved some of the problem with the below code. basically, you were putting a string in the datetime.date() object. The string you were using was the date_format variable, which defined the date_time variable on the next line. I put the date_time variable when you're assigning the temp_date and that error went away.
There is a secondary issue I found with the way you were calling timedelta, I took off the datetime prefix and imported timedelta, which resolved that. The code below runs, but it's not performing the calculations you choose when calling timedelta.
temp_date=datetime.date(date_time)+timedelta()
Changed the class import line as well:
from datetime import datetime, timedelta
I understand that you are trying to get the difference of two dates and print the intermediate dates one day at a time.
I removed certain sections of your code to simplify it and came up with this code that works
EDIT: this code assumes that the user entered date is always older than the current date. You can update the logic to check for the larger date and find the difference accordingly
import datetime
from datetime import datetime
from datetime import timedelta
ask=input("enter date\n")
date_format = "%Y-%m-%d"
day1 = datetime.strptime(ask, date_format)
day2 = datetime.strptime((str(datetime.now().date())), date_format)
diff_of_dates = day2 - day1
diff=diff_of_dates.days
for i in range(1,diff):
temp_date=day1+timedelta(days=i)
print("Difference of day",datetime.strftime(temp_date, date_format))
Output
> python test.py
enter date
2019-03-28
Difference of day 2019-03-29
Difference of day 2019-03-30
Difference of day 2019-03-31

Datetime has no attribute datetime

I want to return datetime.datetime.strptime(date_visit,"%Y-%m-%d") into my function read_file but python keeps saying that datetime.datetime has no attribute datetime? In the function where I return it´s working. Pls help anyone.
return datetime.datetime.strptime(date_visit,"%Y-%m-%d")
def read_file(date):
all_animals = list()
day = datetime.datetime.strptime(date_visit,"%Y-%m-%d").isoweekday()
datetime.datetime.strptime(date_visit,"%Y-%m-%d")
workingday = [1,2,3,4,5]
Just replace import datetime.datetime by import datetime
Of course datetime.datetime does not have the attribute datetime. You should use it like this:
from datetime import datetime
datetime.strptime(...)
Or:
import datetime
datetime.datetime.strptime(...)
To use datetime.datetime.strptime() you need to import the whole module:
import datetime
The second datetime is a type in the first one, and it has strptime() function. For more details please check this link:
datetime — Basic date and time types

How to use python date time function/ increment?

I read many of the similar questions, the function is simple nested for loops used for the API, each minute I can call 5 times. So I set the range of 75 for one year data. Can you guys help me solve the problem? Thanks in advance!
The first part is working, enter the zip code from the list.
for zip in zipcode:
url4 = url1+str(zip)+url2
Second part is not working
for x in range (0,75):
counter = x * 5
startdate += datetime.timedelta(days=counter)
enddate += datetime.timedelta(days=counter)
url = url4+startdate+","+enddate+url3
apifunction(url)
system said:
Traceback (most recent call last):
File "<pyshell#51>", line 3, in <module>
startdate += datetime.timedelta(days=counter)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
Probably you're importing like this
from datetime import datetime
This way you import datetime type from datetime module. And this type of course does not have timedelta type in it.
You should import like this:
import datetime
In this case you simply import datetime module, and when you do datetime.timedelta it means that you want to use type timedelta from module datetime
It looks like datetime is getting redefined somewhere else in your code.
>>> import datetime
>>> type(datetime)
<type 'module'>
Your 'datetime' there is an object, which probably means you made a variable and called it datetime somewhere else in your code.

Converting Twitter XML Date to Python Date Object

I'm trying to convert Twitter's "created_at" tag information from an XML file to a date object in Python. I pieced together some code that gets me most of the way there, but then breaks down when I try to compare the date I found with other date objects. Here's what I have so far:
import time
from datetime import datetime
#Twitter part removed... generates a list of dates from the XML called date_list
#Takes the first item from the list (date_list) and converts it to a string
date_str = str(date_list[0])
#Takes the string (date_str) and converts it to datetime
time_struct = time.strptime(date_str, "%a %b %d %H:%M:%S +0000 %Y")
date_datetime = datetime.fromtimestamp(time.mktime(time_struct))
#Converts datetime to just date
date = date_datetime.date()
if date_datetime < datetime.now():
print "yes"
if date < datetime.date.today():
print "yes, also"
As far as output, I get one yes and then an "AttributeError: 'method_descriptor' object has no attribute 'today'" for the last line.
I tried changing the import to just "import datetime", but then I get the following error AttributeError: 'module' object has no attribute 'fromtimestamp' and no output.
It seems like either I import datetime and the fromtimestamp part of the code stops working or I import "from datetime import datetime" and I can't created date objects? I've seen other threads that help you get from the Twitter date to datetime, but how do you get all the way to date (no minutes, seconds, etc)?
Try datetime.now().date() or datetime.today().date() instead. Otherwise, you also need to from datetime import date to do date.today()

Why does trying to use `datetime.strptime` result in " 'module' object has no attribute 'strptime'"? [duplicate]

This question already has answers here:
AttributeError: 'datetime' module has no attribute 'strptime'
(5 answers)
Closed last month.
I'm using strptime to convert a date string into a datetime. According to the linked page, formatting like this should work:
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
My code is:
import datetime
dtDate = datetime.strptime(sDate,"%m/%d/%Y")
where sDate = "07/27/2012". (I understand, from the same page, that %Y is "Year with century as a decimal number.")
I have tried putting the actual value of sDate into the code:
dtDate = datetime.strptime("07/27/2012","%m/%d/%Y")
but this does not work. The error I get is:
AttributeError: 'module' object has no attribute 'strptime'
What am I doing wrong?
You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.
You are importing the module datetime, which doesn't have a strptime function.
That module does have a datetime object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
Because datetime is the module. The class is datetime.datetime.
import datetime
dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")
You should use strftime static method from datetime class from datetime module. Try:
import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")
You can also do the following,to import datetime
from datetime import datetime as dt
dt.strptime(date, '%Y-%m-%d')
If in the folder with your project you created a file with the name "datetime.py"

Categories

Resources