Python converting string date object to date gives valuerror - python

I'm trying to convert string date object to date object in python.
I did this so far
old_date = '01 April 1986'
new_date = datetime.strptime(old_date,'%d %M %Y')
print new_date
But I get the following error.
ValueError: time data '01 April 1986' does not match format '%d %M %Y'
Any guess?

%M parses minutes, a numeric value, not a month. Your date specifies the month as 'April', so use %B to parse a named month:
>>> from datetime import datetime
>>> old_date = '01 April 1986'
>>> datetime.strptime(old_date,'%d %B %Y')
datetime.datetime(1986, 4, 1, 0, 0)
From the strftime() and strptime() Behavior section:
%B
Month as locale’s full name.
January, February, ..., December (en_US);
Januar, Februar, ..., Dezember (de_DE)
%M
Minute as a zero-padded decimal number.
00, 01, ..., 59

You can first guess the type of date format the string is using and then convert to the same system recognised date format.
I wrote a simple date_tools utilities that you can find here at [https://github.com/henin/date_tools/]
Installation: pip install date-tools
Usage:
from date_tools import date_guesser
from datetime import datetime
old_date = '01 April 1986'
date_format = date_guesser.guess_date_format(old_date)
new_date = datetime.strptime(old_date, date_format)
print(new_date)

Related

time data 'May 10 2021' does not match format '%m %d %Y'

I am having trouble printing a formatted time object produced from a string
This is my code:
date_time_str = 'May 10 2021'
date_time_obj = datetime. strptime(date_time_str, '%m %d %Y')
print("The type of the date is now", type(date_time_obj))
This is the error:
ValueError: time data 'May 10 2021' does not match format '%m %d %Y'
As per This link, for a month in the Month format, you need to use %B , and for a month in the Mth format ('Apr','Jun') , use %b.
You were using %m, which is used for numerical numbers.
The below works as an example:
import time
import datetime
from time import strptime
print("hello world")
date_time_str = 'May 10 2021'
date_time_obj = strptime(date_time_str, '%B %d %Y')
print("The type of the date is now", date_time_obj)
You can also use datetime parser from dateutil package with fuzzy parsing which is extremely useful when parsing non-standard datetime formats or parsing dates from text:
from dateutil import parser as dps
>>> a = 'Today is 11th of June 2021'
>>> d = dps.parse(a, fuzzy=True)
>>> d
Out[5]: datetime.datetime(2021, 6, 11, 0, 0)
>>> b = 'May 10, 2021'
>>> c = dps.parse(b, fuzzy=True)
>>> c
Out[8]: datetime.datetime(2021, 5, 10, 0, 0)

Python Convert unusual date string to datetime format

I have date string like this:
Saturday, 30 Nov, 2013
So it is like Day_Name, Day, Month_Name_3_Letters, Year.
I wonder what is the best way to convert it to datetime format using python?
I using like this:
datetime.strptime((row[7].split(',')[1] + row[7].split(',')[2]).replace(' ',''), "%d%b%Y").strftime("%Y-%m-%d")
Use strptime:
import datetime as dt
s = 'Saturday, 30 Nov, 2013'
d = dt.datetime.strptime(s,'%A, %d %b, %Y')
Result:
>>> d
datetime.datetime(2013, 11, 30, 0, 0)
As you'll see from the reference:
%A Weekday as locale’s full name.
%d Day of the month as a zero-padded decimal number.
%b Month as locale’s abbreviated name.
%Y Year with century as a decimal number.
You can use strptime function and initialize it as the following:
from datetime import datetime
datetime_object = datetime.strptime('Saturday, 30 Nov, 2013', '%A, %d %b, %Y')
print datetime_object
Conversely, the datetime.strptime() class method creates a datetime
object from a string representing a date and time and a corresponding
format string. datetime
In order to see how to use the formats and when, you can see strftime formats
Why don't you use dateutil's parse ?
from dateutil import parser
parser.parse('Saturday, 30 Nov, 2013')
datetime.datetime(2013, 11, 30, 0, 0)
from datetime import datetime
st='Saturday, 30 Nov, 2013'
print datetime.strptime(st,'%A, %d %b, %Y')
OUTPUT
2013-11-30 00:00:00
See strptime() at Tutorials point

Python date conversion?

I'm currently trying to convert a file format into a slightly different style to allow easier importing into a program however I can't quite get my head around how to convert datetime strings between formats. The original I have is the following:
2016-12-15 17:26:45
However the required format for the date time is:
Thu Dec 15 17:19:03 2016
Does anyone know if there is an easy way to convert between these? These values are always in the same place and format so it doesn't need to be too dynamic so to speak outside of recognising what a certain day of the month is (if that can be done at all?)
Update - The conversion has worked for 1 date but not the other weirdly :/ The code to grab the two dates is the following:
startDate=startDate.replace("Started : ","")
startDate=startDate.replace(" (ISO format YYYY-MM-DD HH:MM:SS)","")
startDate=startDate.strip()
startDt = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S')
startDt=startDt.strftime('%a %b %d %H:%M:%S %Y ')
print (startDt)
This part works as inteded and outputs the required format:
"2016-12-15 17:26:45
Thu Dec 15 17:26:45 2016"
The end date part is a bit "ham fisted" so to speak and I'm sure there are better ways to do the re.sub search just to do anything in brackets but I'll edit that later.
endDate=endDate.replace("Ended : ","")
endDate=endDate.strip()
endDate = re.sub("\(.*?\)", "", endDate)
endDate.strip()
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
endDt=endDt.strftime('%a %b %d %H:%M:%S %Y ')
print (endDt)
This part however despite the outputs being an identical format
"2016-12-15 17:26:45
2016-12-15 21:22:11"
produces the following error:
endDt = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')
File "C:\Python27\lib\_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
from datetime import datetime
dt = datetime.strptime('2016-06-01 1:33:45', '%Y-%m-%d %H:%M:%S')
dt.strftime('%a %b %d %H:%M:%S %Y ')
>>> 'Wed Jun 01 01:33:45 2016'
It's a pretty easy task with the Datetime module.
As it's been pointed out, checking the docs will get you a lot of useful info, starting from the directives to feed to the strptime and strftime (respectively, parse and format time) functions which you'll need here.
A working example for you case would be:
from datetime import datetime
myDateString = '2016-12-15 17:26:45'
myDateObj = datetime.strptime(myDateString, '%Y-%m-%d %H:%M:%S')
myDateFormat = myDateObj.strftime('%a %b %d %H:%M:%S %Y')
Check out this section of the docs to have a better understanding of the formatting placeholders.
You can use the datetime module:
from datetime import datetime
string = '2016-12-15 17:26:45'
date = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
date2 = date.strftime("%a %b %d %H:%M:%S %Z %Y")
print(date2)
Output:
Thu Dec 15 17:26:45 2016

Time data does not match specified format

I'm trying to convert a string given in "DD MM YYYY" format into a datetime object. Here's the code for the same:
from datetime import date, timedelta
s = "23 July 2001"
d = datetime.datetime.strptime(s, "%d %m %Y")
However, I get the following error:
ValueError: time data '23 July 2001' does not match format '%d %m %Y'
What's wrong ? Isn't the format specified in the string the same as that specified by "%d %m %Y" ?
%m means "Month as a zero-padded decimal number."
Your month is July so you should use %B, which is "Month as locale’s full name."
Reference: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Like behzad.nouri said, Use d = datetime.datetime.strptime(s, "%d %B %Y").
Or make s = '23 07 2001' and d = datetime.datetime.strptime(s, "%d %m %Y")

Calculating days using string dates in Python

I have dates in the current string format: 'Tue Feb 19 00:09:28 +1100 2013'
I'm trying to figure out how many days have passed between the date in the string and the present date.
I've been able to convert the string into a date.
import time
day = time.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
Use the datetime module instead:
import datetime
day = datetime.datetime.strptime('Tue Feb 19 00:09:28 +1100 2013', '%a %b %d %H:%M:%S +1100 %Y')
delta = day - datetime.datetime.now()
print delta.days
Subtracting two datetime.datetime values returns a datetime.timedelta object, which has a days attribute.
Your strings do contain a timezone offset, and you hardcoded it to match; if the value varies you'll have to use a parser that can handle the offset. The python-dateutil package includes both an excellent parser and the timezone support to handle this:
>>> from dateutil import parser
>>> parser.parse('Tue Feb 19 00:09:28 +1100 2013')
datetime.datetime(2013, 2, 19, 0, 9, 28, tzinfo=tzoffset(None, 39600))
Note that because this result includes the timezone, you now need to use timezone-aware datetime objects when using date arithmetic:
>>> from dateutil import tz
>>> import datetime
>>> utcnow = datetime.datetime.now(tz.tzutc())
>>> then = parser.parse('Tue Feb 19 00:09:28 +1100 2013')
>>> utcnow - then
datetime.timedelta(31, 12087, 617740)
>>> (utcnow - then).days
31
I created a utcnow variable in the above example based of the UTC timezone before calculating how long ago the parsed date was.

Categories