I am trying to find best way to convert "Friday 1st March 2019" or "Saturday 2nd March 2019" to python datetime object.
I tried by splitting, than had thoughts on regex, but I am quite sure there is more 'elegant' way ofdoing it
From string "Friday 1st March 2019" I expect 01-03-2019 or 2019-03-01
TNX!
Maybe not the "best" way, but a very easy way is dateutil's parser
from dateutil import parser
parser.parse("Friday 1st March 2019")
Returns:
datetime.datetime(2019, 3, 1, 0, 0)
It can pretty much be wrapped up as:
from dateutil import parser
from datetime import datetime as dt
dt.strftime(parser.parse("Friday 1st March 2019"), "%d-%m-%Y")
Returning:
'01-03-2019'
Please refer to an already answered question:
How to get the datetime from a string containing '2nd' for the date in Python?
As I can only repeat, solution is to use dateutil parser:
from dateutil.parser import parse
your_string = "Friday 1st March 2019"
date_obj = parse(your_string)
Behind the scenes, I guess the "1st", and "2nd" parts are extracted somehow (e.g. splitting+regex) and simplified to its day value only.
According to an input like that, the common datetime library can be used with proper date format string:
import datetime
simplified_txt = "Friday 1 March 2019"
datetime_obj = datetime.datetime.strptime(simplified_txt,"%A %d %B %Y")
You are going to face issues with 1st, 2nd.
So, try this (without adding any external/third party library):
import re
from datetime import datetime as dt
ds = "Friday 1st March 2019"
parts = ds.split(" ")
ds = "{} {} {} {}".format(
parts[0],
re.sub('[^0-9]','', parts[1]),
parts[2],
parts[3]
)
a = dt.strptime(ds, "%A %d %B %Y")
If you want to make it into a function, do this:
def convdate(s):
parts = s.split(" ")
ds = "{} {} {} {}".format(
parts[0],
re.sub('[^0-9]','', parts[1]),
parts[2],
parts[3]
)
return dt.strptime(ds, "%A %d %B %Y")
Related
I know this has been asked in some form or another, but I'm wondering how to convert a date such as:
Saturday, May 18th, 2019
to something like 2019-05-18 so that I can compare it to other dates. I understand dateutil can do so but unfortunately I'm using Pycharm and it won't let me install that package without upgrading Python from 2.7 to 3. Is there a way to do this simply in Python?
You can use datetime with re module as well:
>>> from datetime import datetime
>>> import re
>>> s = 'Saturday, May 18th, 2019'
>>> datetime.strptime(re.sub('(\d+)(st|nd|rd|th)', '\g<1>', s), '%A, %B %d, %Y')
datetime.datetime(2019, 5, 18, 0, 0)
>>>
And print it nicer:
>>> print(datetime.strptime(re.sub('(\d+)(st|nd|rd|th)', '\g<1>', s), '%A, %B %d, %Y'))
2019-05-18 00:00:00
>>>
The regex solution is preferable in my opinion, but this is a solution without using re, for people not familiar with regexps:
from datetime import datetime
s = 'Saturday, May 18th, 2019'
sl = s.split()
sl[2] = sl[2][:-3] # remove 'th,'
datetime.strptime(' '.join(sl), '%A, %B %d %Y')
By using:
import os,os.path,time,shutil,datetime
print time.ctime(os.path.getmtime("/home/sulata/Documents/source/"))
print time.ctime(os.path.getmtime("/home/sulata/Documents/destination/"))
I'm getting the outputs:
Mon Apr 2 15:56:00 2018
Mon Apr 2 15:56:03 2018
I want to get the time without seconds.
The general method is:
import time
time.strftime(format)
example:
>>>time.strftime("%H:%M:%S")
20:08:40
In your case:
>>> time.strftime("%H:%M")
13:41
>>>time.strftime("%a %b %d %H:%M %Y")
'Mon Apr 02 13:27 2018'
if you want to remove the Zero, you could do something like this...
>>> time.strftime("%a %b "+str(int(time.strftime("%d"))) +" %H:%M %Y")
'Mon Apr 2 13:33 2018'
Use datetime to get the seconds.
Ex:
import os,os.path,time,shutil,datetime
print datetime.datetime.strptime(time.ctime(os.path.getmtime(r"/home/sulata/Documents/source/")), "%a %b %d %H:%M:%S %Y").second
JulioCamPlaz has already provided a decent enough solution, but if you want to maintain the date format, you can use regex for this:
import re
x = time.ctime(os.path.getmtime("/home/sulata/Documents/source/"))
print(re.sub(r':\d{1,2}\s', ' ', x))
What this does is that it removes the final two digits (seconds) of the time which are followed by a space, and replaces it with a space.
Although this may be an over-complicated method, it is short, and gives you the exact same date format without the seconds, and without altering it in any way.
getmtime returns a timestamp, so you can format it using strftime to whatever format you need:
>>> import datetime as dt
>>> import os
>>> mTime = os.path.getmtime("/tmp/xauth-1000-_0")
>>> dt.datetime.fromtimestamp(mTime).strftime("%Y-%m-%d %H:%M")
'2018-04-01 22:07'
Format identifiers can be found in the docs.
You can try this -
>>> import time, os
>>>
>>> x = time.gmtime(os.path.getmtime('/home/abhi/test.file'))
>>>
>>> x
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=2, tm_hour=11, tm_min=19, tm_sec=43, tm_wday=0, tm_yday=92, tm_isdst=0)
>>> x.tm_sec
43
>>> x.tm_hour
11
>>>
Is it possible to use strptime with text like this: Wed 29th Jul 13:02:30. The point is that I want to have proper format to compare dates.
So I'm looking for something like:
datetime.strptime(' '.join(date.split(' ')[1:]), "%d-%m-%h:%m:%s")
Is it possible? If not, what is the best option how to do that?
Get rid of the "th", "st" and "nd" on the date.
Then use:
datetime.strptime("Wed 29 Jul 13:02:30", "%a %d %b %H:%M:%S")
Use re to remove any rd, nd, st, and th then parse normally:
s = "Wed 29th Jul 13:02:30"
from datetime import datetime
import re
dte = datetime.strptime(re.sub("rd|nd|st|th","",s), "%a %d %b %H:%M:%S")
You could also use dateutil to do the work for you :
s= "Wed 29th Jul 13:02:30"
from dateutil import parser
print(parser.parse(s))
I am pretty new to regular expressions and it's pretty alien to me. I am parsing an XML feed which produces a date time as follows:
Wed, 23 July 2014 19:25:52 GMT
But I want to split these up so there are as follows:
date = 23/07/2014
time = 19/25/52
Where would I start? I have looked at a couple of other questions on SO and all of them deviate a bit from what I am trying to achieve.
Use datetime.strptime to parse the date from string and then format it using the strftime method of datetime objects:
>>> from datetime import datetime
>>> dt = datetime.strptime("Wed, 23 July 2014 19:25:52 GMT", "%a, %d %B %Y %H:%M:%S %Z")
>>> dt.strftime('%d/%m/%Y')
'23/07/2014'
>>> dt.strftime('%H/%M/%S')
'19/25/52'
But if you're okay with the ISO format you can call date and time methods:
>>> str(dt.date())
'2014-07-23'
>>> str(dt.time())
'19:25:52'
I'm having a bad time with date parsing and formatting today.
Points for somebody who can parse this date format into a datetime.date or datetime.datetime (I'm not too fussy but I'd prefer .date):
5th November 2010
Using dateutil:
In [2]: import dateutil.parser as dparser
In [3]: date = dparser.parse('5th November 2010')
In [4]: date
Out[4]: datetime.datetime(2010, 11, 5, 0, 0)
Unfortunately, strptime has no format characters for "skip an ordinal suffix" -- so, I'd do the skipping first, with a little RE, and then parse the resulting "clear" string. I.e.:
>>> import re
>>> import datetime
>>> ordn = re.compile(r'(?<=\d)(st|nd|rd|th)\b')
>>> def parse(s):
... cleans = ordn.sub('', s)
... dt = datetime.datetime.strptime(cleans, '%d %B %Y')
... return dt.date()
...
>>> parse('5th November 2010')
datetime.date(2010, 11, 5)
Your preference for date vs datetime is no problem of course, that's what the .date() method of datetime objects is for;-).
Third-party extensions like dateutil can be useful if you need to do a lot of "fuzzy" date parsing (or other fancy date-related stuff;-), by the way.
If the ordinal is constant then:
datetime.strptime(s, '%dth %B %Y')
Else:
date_str = '5th November 2010'
modified_date_str = date_str[0:1] + date_str[3:]
datetime.strptime(modified_date_str, '%d %B %Y')
Or like ~unutbu said use dateutil :)