is there any solution for Datetime error in python? - 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

Related

want to convert json timestamp into normal timestamp (CST Hrs) in python

I am downloading a json file containing timestamp using python . But the timestamp i am getting is below format
`2021-04-01T21:43:52.757Z`
Want to convert into normal timestamp (CST Hrs). I also see that the time is increased by 4 hours when i compare the report manually.
`4/1/2021 5:43:53 PM`
The above hours is 4 hrs less when i compare with json file entry. Please advise me.
You need to use python's datetime module to handle this. The Z in the string actually means time zone 0 or UTC time which is 6 hours ahead of CST not 4:
import datetime
date_object = datetime.datetime.strptime(
"2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)
date_object = date_object - datetime.timedelta(hours=6)
print(
f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)
Which will give this output:
4/1/2021 03:43:52 PM
have to use an f string if you want non zero padded dates because its not available in datetime according to the docs
You can use pytz module to deal with time zones directly and not hardcode them if you want. Or if you are on python 3.9 you can use timezone objects to create timezones yourself

How to Have Python Make a Variable with a Data Two Years Ago from Todays Date

So I need to make a variable in python to have it send off today's date two years ago. I am having to automate a report in Salesforce using Selenium and need to have the form created by a send.keys() method from a variable.
The variable I have for today's date is :
from datetime import date
import time
today = date.today()
current_date = today.strftime("%m/%d/%Y")
However, I need the past date to be that value printed from two years ago.
from datetime import date
import time
today = date.today()
past_date = today.strftime("%m/%d/%Y") - 2*(365)
However, I get this output:
>>> past_date = today.strftime("%m/%d/%Y") - 2*(365)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I presume it has something to with integer operations and string operations being in the same variable, thereby causing a string mismatch. Does anyone have a solution to help me get the date from two years ago in a dynamic way?
This can all be done with standard library.
To specifically address your error, on this line you are turning the date into a string and then trying to subtract numbers from it.
past_date = today.strftime("%m/%d/%Y") - 2*(365)
However to solve your issue we can change the code up a little:
from datetime import date
today = date.today()
current_date = today.strftime("%m/%d/%Y")
try:
past_date = today.replace(year=today.year-2) # the 2 on this line is how many years in the past you need.
except ValueError:
past_date = today.replace(year=today.year-2, day=today.day-1)
print(past_date)
The try-except is to handle leap year issues.
Many thanks to #Ευάγγελος Γρηγορόπουλος I was able to get the following to work based off his comments from How to subtract a day from a date?
I was able to use
from datetime import datetime, timedelta
past_date = datetime.today() - timedelta(days=730)

Python datetime.today() to handle timezone

Hi apologies on basic python datetime question but I am a little confused:
I want to just have a variable the prints today's date, with consideration to the time zone the program I am running it in. Let's say California.
import datetime
import pytz
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Los_Angeles"))
x = pst_now.isoformat()
for x it returns :
2020-01-13T17:43:56.155556-08:00
how can I get it to return:
2020-01-13
I tried:
datetime.datetime.strptime(x, '%Y-%m-%d)
But it did not work
If you're just looking to return the time of the local machine, no need to deal with timezones directly in your code, you can use the now function of datetime.
import datetime
datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
x is a string. pst_now is a datetime object which, when the method .isoformat() is called on it, produces a string.
Solution: call strftime on pst_now:
x = pst_now.strftime('%Y-%m-%d')
You can convert pst_now to a date() object:
pst_now.date().isoformat()
'2020-01-13'

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

Change datetime to Unix time stamp in Python

Please help me to change datetime object (for example: 2011-12-17 11:31:00-05:00) (including timezone) to Unix timestamp (like function time.time() in Python).
Another way is:
import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
Timestamp is the unix timestamp which shows the same date with datetime object d.
import time
import datetime
dtime = datetime.datetime.now()
ans_time = time.mktime(dtime.timetuple())
Incomplete answer (doesn't deal with timezones), but hopefully useful:
time.mktime(datetime_object.timetuple())
** Edited based on the following comment **
In my program, user enter datetime, select timezone. ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list.
Pytz module provides the necessary conversions. E.g. if dt is your datetime object, and user selected 'US/Eastern'
import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
The argument is_dst=True is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime).

Categories

Resources