I have an input which may contain a date, or time, or both. In case the date is provided I can use that date but in case the date is not provided (i.e. only the time is provided) then I have to use a different date provided from someplace else.
But once I parse the date using using python dateutil, today's date is added to the parsed value. For example:
from dateutil.parser import parse
print(parse('03:15:08'))
print(parse('04-04-2019 03:15:08'))
the above code gives the following output:
2019-04-04 03:15:08
2019-04-04 03:15:08
As you can see the information (that the date was provided or not) is lost and can't be differentiated.
Also some kind of length manipulation may not work because only the date may be provided.
How to differentiate between the 2 inputs?
Thank you.
Related
within a dataset, there are several different datetime-strings.
For example:
2020-11-16T06:00:00Z
2020-11-16T06:00:00+01:00
2020-11-16T06:00:00+01:00Z
2020-11-16T06:00:00+02:00
2020-11-16T06:00:00.000Z
I thought about replacing everything after the seconds, but it gives me errors, when for example +01:00 isn't given in the first place.. or else.
Do you have any clou, how to handle this?
It would be absolutely enough, if I could get:
%Y-%m-%dT%H:%M
(The basics, how to strp and strf are known...)
I've wrangled my head all night about this problem.
Hope, that one of you have got a solution...
thank you in advance!
Python has a standard library that deals with this problem:
import dateutil.parser
examples = [
'2020-11-16T06:00:00Z',
'2020-11-16T06:00:00+01:00',
'2020-11-16T06:00:00+01:00Z',
'2020-11-16T06:00:00+02:00',
'2020-11-16T06:00:00.000Z'
]
for e in examples:
try:
print(dateutil.parser.parse(e))
except ValueError:
print(f'Invalid datetime: {e}')
Result:
2020-11-16 06:00:00+00:00
2020-11-16 06:00:00+01:00
Invalid datetime: 2020-11-16T06:00:00+01:00Z
2020-11-16 06:00:00+02:00
2020-11-16 06:00:00+00:00
#Z4-tier also has a solution for your examples(be careful with just leaving off the end of the string though), but dateutil will also deal with more exotic stuff:
print(dateutil.parser.parse('15:45 16 Nov 2020'))
Result:
2020-11-16 15:45:00
Also note this:
print(dateutil.parser.parse(e).tzinfo)
If you add that, you'll see that dateutil includes the information about the time zone in the result, which would be lost if you only parse the first part of the strings.
how about this:
import datetime
dates = ['2020-11-16T06:00:00Z',
'2020-11-16T06:00:00+01:00',
'2020-11-16T06:00:00+01:00Z',
'2020-11-16T06:00:00+02:00',
'2020-11-16T06:00:00.000Z']
for d in dates:
datetime.datetime.fromisoformat(d[0:19])
Since each date has the same format up to the offset and timezone, just strip that part off of the string and cast it to a datetime.datetime.
The dataset is generated by a scraper, which scrapes news pages.
Therefore the datetime is scraped as string in the first place, so that the conversion has to take place for several different occurrences, before a strptime can be executed.
I found a solution for my problem, which was influenced by all of the approaches of you guys.
'''
date = '2020-11-16T06:00:00+01:00'
splitat = 19
date = date[:splitat]
date
'''
This resulted in the standardized format, which I needed:
'2020-11-16T06:00:00'
I need to return the date format from a string. Currently I am using parser to parse a string as a date, then replacing the year with a yyyy or yy. Similarly for other dates items. Is there some function I could use that would return mm-dd-yyyy when I send 12-05-2018?
Technically, it is an impossible question. If you send in 12-05-2018, there is no way for me to know whether you are sending in a mm-dd-yyyy (Dec 5, 2018) or dd-mm-yyyy (May 12, 2018).
One approach might be to do a regex replacement of anything which matches your expected date pattern, e.g.
date = "Here is a date: 12-05-2018 and here is another one: 10-31-2010"
date_masked = re.sub(r'\b\d{2}-\d{2}-\d{4}\b', 'mm-dd-yyyy', date)
print(date)
print(date_masked)
Here is a date: 12-05-2018 and here is another one: 10-31-2010
Here is a date: mm-dd-yyyy and here is another one: mm-dd-yyyy
Of course, the above script makes no effort to check whether the dates are actually valid. If you require that, you may use one of the date libraries available in Python.
I don't really understand what you plan to do with the format. There are two reasons I can think of why you might want it. (1) You want at some future point to convert a normalized datetime back into the original string. If that is what you want you would be better off just storing the normalized datetime and the original string. Or (2) you want to draw (dodgy) conclusions about person sending the data, because different nationalities will tend to use different formats. But, whatever you want it for, you can do it this way:
from dateutil import parser
def get_date_format(date_input):
date = parser.parse(date_input)
for date_format in ("%m-%d-%Y", "%d-%m-%Y", "%Y-%m-%d"):
# You can extend the list above to include formats with %y in addition to %Y, etc, etc
if date.strftime(date_format) == date_input:
return date_format
>>> date_input = "12-05-2018"
>>> get_date_format(date_input)
'%m-%d-%Y'
You mention in a comment you are prepared to make assumptions about ambiguous dates like 12-05-2018 (could be May or December) and 05-12-18 (could be 2018 or 2005). You can pass those assumptions to dateutil.parser.parse. It accepts boolean keyword parameters dayfirst and yearfirst which it will use in ambiguous cases.
Take a look at the datetime library. There you will find the function strptime(), which is exactly what you are looking for.
Here is the documentation: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
I'm using Instagram-API-python to create an application. I'm getting a JSON response with below value.
'device_timestamp': 607873890651
I tried to convert this value to readable using python.
import time
readable = time.ctime(607873890651)
print(readable)
It gives following result and seems it is not correct.
Sun Oct 3 16:00:51 21232
I'm not much familiar with the Instagram-API-python. Please someone can help me to solve this problem.
The data is very likely to be incorrect.
Timestamp is a very standard way to store a date-time. Counting the seconds that passed since January 1st, 1970, also known as the UNIX Epoch.
I looked for "Instagram 'device_timestamp'" on Google and all the user-provided values made sense, but yours doesn't.
This is probably an error from the database, it happens.
Use the mentioned ctime conversion, but take the 'taken_at' field if available.
Don't use device_timestamp but use taken_at field. Then taken_at need multiply to 1000.
In Java it looks like this
Date data = new Date(taken_at * 1000);
I have some text, taken from different websites, that I want to extract dates from. As one can imagine, the dates vary substantially in how they are formatted, and look something like:
Posted: 10/01/2014
Published on August 1st 2014
Last modified on 5th of July 2014
Posted by Dave on 10-01-14
What I want to know is if anyone knows of a Python library [or API] which would help with this - (other than e.g. regex, which will be my fallback). I could probably relatively easily remove the "posed on" parts, but getting the other stuff consistent does not look easy.
My solution using dateutil
Following Lukas's suggestion, I used the dateutil package (seemed far more flexible than Arrow), using the Fuzzy entry, which basically ignores things which are not dates.
Caution on Fuzzy parsing using dateutil
The main thing to note with this is that as noted in the thread Trouble in parsing date using dateutil if it is unable to parse a day/month/year it takes a default value (which is the current day, unless specified), and as far as i can tell there is no flag reported to indicate that it took the default.
This would result in "random text" returning today's date of 2015-4-16 which could have caused problems.
Solution
Since I really want to know when it fails, rather than fill in the date with a default value, I ended up running twice, and then seeing if it took the default on both instances - if not, then I assumed parsing correctly.
from datetime import datetime
from dateutil.parser import parse
def extract_date(text):
date = {}
date_1 = parse(text, fuzzy=True, default=datetime(2001, 01, 01))
date_2 = parse(text, fuzzy=True, default=datetime(2002, 02, 02))
if date_1.day == 1 and date_2.day ==2:
date["day"] = "XX"
else:
date["day"] = date_1.day
if date_1.month == 1 and date_2.month ==2:
date["month"] = "XX"
else:
date["month"] = date_1.month
if date_1.year == 2001 and date_2.year ==2002:
date["year"] = "XXXX"
else:
date["year"] = date_1.year
return(date)
print extract_date("Posted: by dave August 1st")
Obviously this is a bit of a botch (so if anyone has a more elegant solution -please share), but this correctly parsed the four examples i had above [where it assumed US format for the date 10/01/2014 rather than UK format], and resulted in XX being returned appropriately when missing data entered.
You could use Arrow library:
arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'MM-DD-YYYY'])
Two arguments, first a str to parse and second a list of formats to try.
I want to know how to convert different format dates to expected format in python .
ex : i want to get this format : 2/29/2012
['2012-02-01 // 2012-02-28', '2/15/2012', '2/13/2012', '2/14/2012', '2/23/2012', '2/18/2012', '2/29/2012']
How to check today date in the range '2012-02-01 // 2012-02-28'
Share your suggestions
Use the datetime library in python. You can just compare two different datetime.datetime objects. And you can separate the year, month, date thing to put it in anyform you want.
Check this link for all the library details.
http://docs.python.org/library/datetime.html
Hope that helped.
The dateutil python library parses a wider variety of date formats than the standard datetime module.