I understand my question title may be a little vague so let me explain.
I need to check to see if an object has gone past a certain date. Now here's what makes it complicated. When the object is added to the model it's only done so with a string date not actually formatted as a date. It's coming from CSV so it's the only way I can do this.
It will always be formatted as M-DD-YY.
Now, what I need to check for is to see if a reset has happened. Resets occur every Wednesday at 4am CEST. So when I'm looking at the model I can have it set as two things.
Expired objects (from the previous reset)
Current objects (that will not reset until next Wednesday)
I really can't figure out the best way to tackle this and I am open to ideas and suggestions.
Thank you.
Convert the field into a datetime in code using dateutil.parser before comparing it to the current date:
from dateutil import parser
from datetime import datetime
object_date = parser.parse(my_obj.datefield)
if object_date < datetime.now():
# Do something
else:
# Do something else
You can install dateutil using pip install python-dateutil
Related
I'd like to convert this list of strings of various unknown date formats to a python datetime object. For example:
strings = ["today", "tomorrow", "next Friday", "June 4th", "04/11/2022"]
convert_to_date(strings[0])
>>> 2022-04-08
convert_to_date(strings[1])
>>> 2022-04-09
convert_to_date(strings[3])
>>> 2022-04-15
I tried several methods but found that:
dateutil.parser only works for dates like 04/11/2022
time.strptime and arrow both require me to specify the format
regex would be too complicated and may not work for all scenarios
Is there any library or function that would allow me to do something like this?
TL;DR No Library
I don't think there is any library or function to do the thing you're asking to.
This question seems like one of those coding challenges you see on various code challenge websites.
You have to essentially create your own algorithm(function) to do this stuff.
You can ask specific questions along the way of crushing this challenge.(which are Trust Me more likely to get answered ! )
Since i think you're a beginner i,ll give you a Headstart!!
Here's some sample code to help you out (in python)
import datetime
def crazyDateToStandard(crazyDate):
today = datetime.date.today()
if(crazyDate=='today'):
print("Today's date:",today)
elif(crazyDate=='tomorrow'):
tomorrow = today + datetime.timedelta(days=1)
print("Tommorow's date:",tomorrow)
#shows today's date
crazyDateToStandard('today')
#shows tommorow's date
crazyDateToStandard('tomorrow')
I have implemented a basic functionality here, its now upto you to figure this code out and ask yourself.
What does each of these functions do?
How i can use it?
How can i implement it to my algorithm?
Let your curiosity GROW!!
This is why we code.
To do our own little unique things and also to contribute to the community.
All those libraries that made our lives easier wouldn't have existed if it weren't for the dedication and passion of millions or even billions of people around the globe.
So Go ahead and destroy this challenge FAM!
Why the followings return different timestamp? Is it because datetime.utcnow() doesn't have a timezone? It looks to me that tzinfo=utc is redudant, so I am probably not getting what is utcnow() and how an UTC number could not have a timezone. I guess there is a reason, so please enlight me :)
from datetime import datetime
from pytz import utc
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
My goal is to get the UTC timestamp. It looks like the first method returns the local timestamp (correct me if I am wrong)
EDIT:
Where I live the timezone is GMT-5. In fact:
(utc_seconds-local_seconds)/3600 # is equal to -5.0
Following two statements would always return different result.
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
Output:
1585584790
1585604590
You ask why? Because, by the time first statement executes, there is some time spent during execution and now the second statement would fetch you different result because datetime.utcnow() for 2nd statement has changed.
What I assume is, you want to see if both operations would give the same result or not? They definitely would have given the same results :
Had you provided them the same input?
Had you performed the similar operation from a common library.
To solve 1. change your code like this.
same_time_input = datetime.utcnow()
local_seconds = int(same_time_input.timestamp())
utc_seconds = int(same_time_input.replace(tzinfo=utc).timestamp())
Still the output would not be same, because you are using an external library, and the replace function is not working as you expected.
If you printout the tzinfo from same_time_input, you would see that it doesn't have any timezone info reason of which can be read here. --> Why does datetime.datetime.utcnow() not contain timezone information?
print(same_time_input.tzinfo)
Now, you are trying to give it a timezone info using a separate library which has different implementation internally resulting in slightly off results.
So this question is more of best way to handle this sort of input in python. Here is an example of input date 2018-12-31 23:59:59.999999. The millisecond part may or may not be part of input.
I am currently using this code to convert this to datetime
input_ts = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%S.%f')
But the problem in this case is that it will throw an exception if input string doesn't contain milliseconds part i.e., 2018-12-31 23:59:59
In Java, I could have approached this problem in two ways. (its a pseudo explanation, without taking into account of small boundary checks)
(preferred approach). Check the input string length. if its less than 19 then it is missing milliseconds. Append .000000 to it.
(not preferred). Let the main code parse the string, if it throws an exception, then parse it with new time format i.e., %Y-%m-%dT%H:%M:%S
The third approach could be just strip off milliseconds.
I am not sure if python has anything built-in to handle these kind of situations. Any suggestions?
You could use python-dateutil library, it is smart enough to parse most of the basic date formats.
import dateutil.parser
dateutil.parser.parse('2018-12-31 23:59:59.999999')
dateutil.parser.parse('2018-12-31 23:59:59')
In case you don't want to install any external libraries, you could iterate over list of different formats as proposed in this answer.
from datetime import datetime # import datetime class from datetime package
dt = datetime.now() # get current time
dt1 = dt1.strftime('%Y-%m-%d %H:%M:%S') # converting time to string
dt3 = dt2.strptime('2018/5/20','%Y/%m/%d') # converting a string to specified time
Since the start and end times of DST in a timezone can change every year, so how does python tell if dst is in effect or not?
At the very top of the CPython source code for the datetime module, it gives the source of the data:
"""Concrete date/time and related types. See
http://www.iana.org/time-zones/repository/tz-link.html for time zone
and DST data sources. """
Presumably this may be variable over time.
Actually my old answer was wrong. In the python shell you can do:
>>> import time
>>>time.localtime()
here it will show a result
>>> _.tm_isdst
This question is actually a duplicate but the old post can be found here:
Python daylight savings time
I tried to submit a time var with value of 2016-03-12T01:47:57+00:00 in a timestamp field, it gives me error saying to check the syntax for errors, however when I use a function to normalize the date
t = datetime.datetime.strptime(data['time'], '%Y-%m-%dT%H:%M:%SZ').strftime('%Y-%m-%d:%H:%M:%S')
I get an error like this.
time data '2016-03-12T01:47:57+00:00' does not match format '%Y-%m-%dT%H:%M:%SZ'
What's causing your problem has already been clarified by others, but please allow me to suggest my favorite solution for cases such as yours:
from dateutil import parser
parser.parse(data['time'])
More about the dateutil module here.
There are a few problems here:
The %Z (note the captial Z!) is for time zone, for example GMT. I
think you want the lower case option: %z, which is for UTC offset.
You can read here in the docs what all the options do :)
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
You need the % symbol before each option. You cannot write %Sz, you must write %S%z. Otherwise Python is trying to match something like 2016-03-12T01:47:57z, rather than 2016-03-12T01:47:57+00:00
Unfortunately, you can't use the %z option with strptime, see this answer:
ISO to datetime object: 'z' is a bad directive
My solution:
It sounds like you don't even want to use the UTC offset. That's fine! If you can't change the way your date string is generated, perhaps this is the best option (though it's maybe a little dirty):
t = datetime.datetime.strptime(data['time'][:-6], '%Y-%m-%dT%H:%M:%S')
This will remove the UTC offset from the string.
If you can change the way your datetime string is being generated, that would be a better solution, but I realise you might not be able to do so.
I hope this helps!