I am looking to retrieve the next possible date for a weekday contained in a string. Complexity being that this weekday will be in foreign language (sv_SE).
In bash I can solve this using `dateround´:
startdate=$(dateround --from-locale=sv_SE -z CET today $startday)
Highly appreciate your guidance on how to solve this in Python.
Thank you very much!
Dateparser has support for quite a few languages. You could parse the weekday to a datetime object then determine the next possible date available.
-- Edit --
from dateparser import parse
parse('Onsdag').isoweekday() # 3
Now that you have the iso weekday, you can find the next possible date. You can refer to this to see how.
It seems locale aliases are platform specific and case sensitive. I've windows. So locale will be sv_SE.
You can use babel for date/time conversion and is much more comprehensive than native locale module.
Babel is an integrated collection of utilities that assist in internationalizing and localizing Python applications, with an emphasis on web-based applications.
Which can be installed as:
pip install Babel
Once installed, we can use format_date , format_datetime , format_time utilities to format one language date , time to other.
You can use these utilities to convert date/time data between English and Swedish.
>>>import datetime
>>>from babel.dates import format_date, format_datetime, format_time
#Here we get current date time in an datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2017, 10, 31, 9, 46, 32, 650000)
#We format datetime object to english using babel
>>> format_date(now, locale='en')
u'Oct 31, 2017'
#We format datetime object to sweedish using babel
>>> format_date(now, locale='sv_SE')
u'31 okt. 2017'
>>>
Related
I'm scraping a a page that includes among other things, date information. So I have a variable named warrant_issued that contains u'11/5/2003' -- I want to store this as a machine readable date. PHP has a handy strtotime function that works fabulously. I was hoping that datetime's strptime would help me but it doesn't seem to be available in my version of datetime -- here is everything in my tab complete on datetime.
In [231]: datetime.
datetime.MAXYEAR datetime.__hash__ datetime.__sizeof__
datetime.MINYEAR datetime.__init__ datetime.__str__
datetime.__class__ datetime.__name__ datetime.__subclasshook__
datetime.__delattr__ datetime.__new__ datetime.date
datetime.__dict__ datetime.__package__ datetime.datetime
datetime.__doc__ datetime.__reduce__ datetime.datetime_CAPI
datetime.__file__ datetime.__reduce_ex__ datetime.time
datetime.__format__ datetime.__repr__ datetime.timedelta
datetime.__getattribute__ datetime.__setattr__ datetime.tzinfo
I'm using iPython 2.7.2+
Am I barking up the wrong tree here? What's the best way to turn u'11/5/2003' into a date?
strptime() is definitely the right approach, it's just a class method for the datetime class (confusingly part of the datetime module).
That is, datetime.datetime.strptime() is what you're looking for (and not datetime.strptime().
Try this:
For use with the datetime module, documentation here
>>>import datetime
>>>a = u'11/5/2003'
>>>time1 = datetime.datetime.strptime(a, "%m/%d/%Y")
>>>print time1
datetime.datetime(2003, 11, 5, 0, 0)
In ipython:
In [1]: import datetime
In [2]: a = u'11/5/2003'
In [3]: time1 = datetime.datetime.strptime(a, "%m/%d/%Y")
In [4]: print time1
2003-11-05 00:00:00
Use with the time module, documentation here
>>>import time
>>>a = u'11/5/2003'
>>>time1 = time.strptime(a, "%m/%d/%Y")
>>>print time1
time.struct_time(tm_year=2003, tm_mon=11, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=309, tm_isdst=-1)
Thanks to the comment reply from #David Cain:
The dateutil library can parse datetime strings (inferring their format). However, note that "11/5/2003" is not an unambiguous format (MM/DD or DD/MM differs by locale), so dateutil should be used with caution in this case. – David Cain
So an alternative good practice is to use the dateutil library:
>>> from dateutil.parser import parse
>>> dt = parse('2016/12/05 05:18 pm')
>>> dt
datetime.datetime(2016, 12, 5, 17, 18)
>>> dt.timestamp()
1480929480.0
>>> parse('16/11/12')
>>> datetime.datetime(2012, 11, 16, 0, 0)
strtotime you use to work with in PHP may be most similar to dateparser.
Note if you don't have the dateparser library.
Install it with
pip3 install dateparser
If you are using conda
conda install dateparser
This library understands over 200 language locales plus numerous formats in a language agnostic fashion.
Parsing generic terms also works:
import dateparser
print (dateparser.parse('yesterday')) #2019-05-19 08:08:14.934992
And also supports non-Gregorian calendar systems.
I have found answers to question like this one helpful but not complete for my problem.
I have a form where the user automatically produces a date. I would like to store that as a date time.
I don't need any of the information after the seconds, but I cannot find a datetime.datetime.strptime code to translate the remaining stuff. So I would either like a strptime code that works for python2.7 on google app engine, or a string editing trick for removing the extra information that is not needed.
date-from-user='2012-09-22 07:36:36.333373-05:00'
You can slice your string to only select the first 19 characters:
>>> datefromuser='2012-09-22 07:36:36.333373-05:00'
>>> datefromuser[:19]
'2012-09-22 07:36:36'
This let's you parse the date without having to bother with the microseconds and timezone.
Do note that you probably do want to parse the timezone too though. You can use the iso8601 module to handle the whole format, without the need to slice:
>>> import iso8601
>>> iso8601.parse_date(datefromuser)
datetime.datetime(2012, 9, 22, 7, 36, 36, 333373, tzinfo=<FixedOffset '-05:00'>)
The iso8601 module is written in pure python and works without problems on the Google App Engine.
Python Docs would be a good place to start. strptime() would be your best option.
import datetime
datefromuser = '2012-09-22 07:36:36.333373-05:00'
datetime.datetime.strptime(datefromuser.split(".")[0], "%Y-%m-%d %H:%M:%S")
2012-09-22 07:36:36
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
Totally new to python, I'm actually working on an ex-colleague's script. in looking at it it seems fairly straight-forward. Here's the situation:
The script looks at current localtime (UTC) and renders a time-based table that scrolls/changes throughout the day as the hours pass so there's always a rolling 8 hour table.
The problem is that now we'd like to deploy a copy of this tool (on the same server) in CST ('America/Chicago') (meaning I need to change the UTC time to CST) so I'm just trying to find a way to modify what he has to make the 'current_time' variable == GMT -6.
He used strftime() to get the first hour:
current_time = int(strftime("%H"))
if current_time <19:
temp_page.write(...)
elif current_time == 19:
temp_page.write(...)
etc.
So - from my php knowledge, I'd love to be able to do something like:
current_time = int(strftime("%H"), (localtime() -6 hours))
(yes, I realize that's not real php code, but hopefully you get my meaning ;-))
In my research, I've come across pytz, but this is not installed on the webserver, though I can probably get it if that's the best/easiest way too implement it.
Any help is greatly appreciated.
Yes, try to install pytz, it will help you a lot when working with different timezones (and UTC).
The current UTC time (independent from the timezone of your computer) can be obtained with:
import pytz
from datetime import datetime
now = datetime.now(pytz.utc)
now is now datetime.datetime(2011, 11, 30, 14, 26, 30, 628014, tzinfo=<UTC>) and you can use it to calculate the current UTC hour with now.hour (returns 14)
You could probably use the datetime module (it's part of the standard library, so it's installed if a standard python is on the system).
In particular, datetime objects can have an optional tzinfo attribute, used during timezone conversions. Here's a blog post that explains step-by-step how to use those.
Does anyone know how to parse the format as described in the title using Pythons strptime method?
I have something similar to this:
import datetime
date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z')
I can't seem to figure out what kind of timeformat this is. By the way, I'm a newbie at the Python language (I'm used to C#).
UPDATE
This is how I changed the code based on the advise (answers) below:
from dateutil.parser import *
from datetime import *
date = parse(entry.published.text)
That date is in ISO 8601, or more specifically RFC 3339, format.
Such dates can't be parsed with strptime. There's a Python issue that discusses this.
dateutil.parser.parse can handle a wide variety of dates, including the one in your example.
If you're using an external module for XML or RSS parsing, there is probably a routine in there to parse that date.
Here's a good way to find the answer: using strftime, construct a format string that will emit what you see. That string will, by definition, be the string needed to PARSE the time with strptime.
If you are trying to parse RSS or Atom feeds then use Universal Feed Parser. It supports many date/time formats.
>>> import feedparser # parse feed
>>> d = feedparser.parse("http://stackoverflow.com/feeds/question/3946689")
>>> t = d.entries[0].published_parsed # get date of the first entry as a time tuple
>>> import datetime
>>> datetime.datetime(*t[:6]) # convert time tuple to datetime object
datetime.datetime(2010, 10, 15, 22, 46, 56)
That's the standard XML datetime format, ISO 8601. If you're already using an XML library, most of them have datetime parsers built in. xml.utils.iso8601 works reasonably well.
import xml.utils.iso8601
date = xml.utils.iso8601.parse(entry.published.text)
You can look at a bunch of other ways to deal with that here:
http://wiki.python.org/moin/WorkingWithTime
I originally posted this question looking for an answer with using python, got some good help, but have still not been able to find a solution. I have a script running on OS X 10.5 client machines that captures internet browsing history (required as part of my sys admin duties in a US public school). Firefox 3.x stores history in a sqlite db, and I have figured out how to get that info out using python/sqlite3. Firefox 3.x uses a conventional unixtimestamp to mark visits and that is not difficult to convert... Chrome also stores browser history in a sqlite db, but its timestamp is formatted as the number of microseconds since January, 1601. I'd like to figure this out using python, but as far as I know, the sqlite3 module doesn't support that UTC format. Is there another tool out there to convert Chrome timestamps to a human readable format?
Use the datetime module. For example, if the number of microseconds in questions is 10**16:
>>> datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=1e16)
datetime.datetime(1917, 11, 21, 17, 46, 40)
>>> _.isoformat()
'1917-11-21T17:46:40'
this tells you it was just past a quarter to 6pm of November 21, 1917. You can format datetime objects in any way you want thanks to their strftime method, of course. If you also need to apply timezones (other than the UTC you start with), look at third-party module pytz.
Bash
$ date -ud #$[13315808702856828/10**6-11644473600] +"%F %T %Z"
2022-12-18 03:45:02 UTC
$ printf '%(%FT %T %z)T\n' $[13315808702856828/10**6-11644473600]
2022-12-17 T19:45:02 -0800
Perl
$ echo ".. 13315808702856828 .." |\
perl -MPOSIX -pe 's!\b(1\d{16})\b!strftime(q/%F/,gmtime($1/1e6-11644473600))!e'
.. 2022-12-17 ..