Converting Twitter XML Date to Python Date Object - python

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

Related

Converting string to datetime with strptime in Python

I'm trying to convert a string to datetime with dd/mm/YYYY format, but the function "strptime" seems isn't working properly. The result format isn't in the same that i am specifying in the function.
import datetime
from datetime import datetime
from datetime import date
today = date.today()
print (today)
today = today.strftime("%d-%m-%Y %H:%M:%S")
print (today)
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
My output is this:
2022-08-26
26-08-2022 00:00:00
2022-08-26 00:00:00
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
That part is creating a datetime object.
You can do:
print (today.strftime("%d-%m-%Y %H:%M:%S"))
again in the final line
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
That is because print(today) determines the format since you didn't specify one. As other's pointed out, today is a datetime object. When you print() a datetime object, python will choose a format for you, I assume based on your system's locale settings.
One concept to understand here is the difference between a value and the representation of that value as a string. This is what formatting a datetime is for.
I suggest you don't worry about the output here too much. As long as your explicit format with strftime() gives you the correct representation, then you are good. This formatting should only be used for output. Otherwise, store datetimes and datetime objects in your variables.

Convert json field to datetime in Python

I get time data from API response like '2020-02-25T20:53:06.706401+07:00'. Now I want to convert to %Y-%m-%d %H:%M:%s format. But I do not know exactly standard format of that time data.
Help me find the time format!
In your case you can use datetime.fromisoformat:
from datetime import datetime
datetime_object = datetime.fromisoformat("2020-02-25T20:53:06.706401+07:00")
print(datetime_object.strftime("%Y-%m-%d %H:%M:%s"))
Prints
2020-02-25 20:53:1582656786
Other options:
Use the third party dateutil library
Use datetime.strptime which parses the string according to format
You can convert to a datetime object and then optionally recreate the string in a new format as follows:
from datetime import datetime
d = "2020-02-25T20:53:06.706401+07:00"
dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
# Note the capital S
new = dt.strftime("%Y-%m-%d %H:%M:%S")
However the new value here has lost the timezone offset information. I assume that's OK for you. I also used %S instead of %s since I assume that's really what you want. The lowercase %s wouldn't really make sense, and is also not truly supported by Python.

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

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

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

Python Datetime object

I am currently having an issue converting an incoming datetime string to a datetime object using Python's built in strptime() method. Here is what I currently have:
def fixDateTimeField(datetimeString):
# Convert from 2012-08-07T00:00:00Z to 2012-08-07T00:00:00.000Z
datetime_object = datetime.strptime(datetimeString, "%y-%m-%dT%H:%M:%SZ")
return datetime_object
Like the comment says, I am trying to convert the string "2012-08-07T00:00:00Z" to a datetime object that looks like 2012-08-07T00:00:00.000Z but I am getting an error in my console that says: "ValueError: time data '2012-08-07T00:00:00Z' does not match format '%y-%m-%dT%H:%M:%SZ'". The format seems correct to me and i'm not seeing the issue.
Thanks in advance!
%y is for two-digit years. You have a four-digit year.
Try using %Y instead.
>>> from datetime import datetime
>>> datetimeString = "2012-08-07T00:00:00Z"
>>> print(datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ"))
2012-08-07 00:00:00
A nice way to parse your iso-8601 datetime string "2012-08-07T00:00:00Z" to a datetime object is using dateutil.
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
With strptime:
datetime.datetime.strptime( "2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")
Works. As an other answer said, the Y must be capitalized for strptime to work with 4 digit years.

Categories

Resources