Strptime - text format contains written month names - python

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

Related

Convert different date strings to unix timestamp in python 3.6

I have two strings. How can I convert them to UNIX timestamp (eg.: "1284101485")? (Please observe that 1284101485 is not the correct answer for this case.)
I don't care about time zones as long as it is consistent.
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
You can use dateparser
Install:
$ pip install dateparser
Sample code:
import dateparser
from time import mktime
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
datetime1 = dateparser.parse(string_1_to_convert)
datetime2 = dateparser.parse(string_2_to_convert)
unix_secs_1 = mktime(datetime1.timetuple())
unix_secs_2 = mktime(datetime2.timetuple())
print(unix_secs_1)
print(unix_secs_2)
Output:
1561492438.0
1561488838.0
The above implementation gives you a consistent response and doesn't give you an error when trying to parse CEST.
you can use .strptime to parse by a format you specify.
try this:
import datetime
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
ts1 = datetime.datetime.strptime(string_1_to_convert, "%a %b %d %H:%M:%S %Z %Y").timestamp()
ts2 = datetime.datetime.strptime(string_2_to_convert, "%Y-%m-%d %H:%M:%S").timestamp()
print(ts1)
print(ts2)
NOTICE: the CEST part might be non-portable, as strptime only knows how to parse timezones that appear in time.tzname.

Python Identify (Convert) text to date

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

How to convert a string into a date variable with a particular format

I have found a question at this link that almost answers what I need but not quite. What I need to know, how using this method could I convert a string of the format u'Saturday, Feb 27 2016' into a Python date variable in the format 27/02/2016?
Thanks
You have to first remove the weekday name (it's not much use anyway) and parse the rest:
datetime.datetime.strptime('Saturday, Feb 27 2016'.split(', ', 1)[1], '%b %d %Y').date()
Alternatively, use dateutil:
dateutil.parser.parse('Saturday, Feb 27 2016').date()
EDIT
My mistake, you don't need to remove the Weekday (I'd missed it in the list of options):
datetime.datetime.strptime('Saturday, Feb 27 2016', '%A, %b %d %Y').date()
You don't have to remove anything, you can parse it as is and use strftime to get the format you want:
from datetime import datetime
s = u'Saturday, Feb 27 2016'
dt = datetime.strptime(s,"%A, %b %d %Y")
print(dt)
print(dt.strftime("%d/%m/%Y"))
2016-02-27 00:00:00
27/02/2016
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%d Day of the month as a decimal number [01,31].
%Y Year with century as a decimal number.
The full listing of directives are here

Twitter created_at convert epoch time in python

I have this date from Twitter:
created_at = "Wed Aug 29 17:12:58 +0000 2012"
I want to convert it to a time using something like:
time.mktime(created_at)
But I get this error:
TypeError: argument must be 9-item sequence, not str
What am I doing wrong?
You need to convert the incoming string to a Python time tuple using strptime before you can do anything with it.
This code will take the input string, convert it to a tuple and then converts that to a Unix-epoch time float using time.mktime:
import time
created_at = "Wed Aug 29 17:12:58 +0000 2012"
print time.mktime(time.strptime(created_at,"%a %b %d %H:%M:%S +0000 %Y"))
I don't if it too late, use arrow package instead could fewer imports and a lot less code.
pip install arrow
Then:
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y")
<Arrow [2012-08-29T17:00:58+00:00]>
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y").timestamp
1346259658
Read the documentation of time.mktime
It requires struct_time, or you can alternatively represent it using a 9-tuple.
The required entries are:
Year
Month
Date
Hour
Minute
Second
Day in week
Day in year
Daylight Savings Time
This is not the function you need, however. It seems that you want to use strptime instead.
According to the documentation:
Parse a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
So, you can do:
time.strptime(created_at)

date format with timezone

How do I format a date in python to look like this: weekday:month:day(number):HH:MM:SS(military):EST/CST/PST:YYYY? I am familiar with strftime(), but I am unsure how I would handle the HH:MM:SS and EST/CST/PST.
example of how I am trying to get the date to look:
Sun Mar 10 15:53:00 EST 2013
from time import gmtime, strftime
print strftime("%a %b %d %H:%M:%S %Z %Y", gmtime())
This will produce
Fri Mar 22 21:10:56 Eastern Standard Time 2013
You'll have to settle for the long name of the timezone unless you want to use pytz. I suppose it's worth noting that timezone abbreviations aren't unique.
Use strftime to output a formatted string representation:
print time.strftime("%a %b %d %H:%M:%S %Z %Y")
A list of the format codes can be found here

Categories