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")
Related
I am trying to parse the mailing list of Apache Pig. I use the following function while parsing the dates.
from datetime import datetime
def str_to_date(date_str):
# First, remove the (UTC) type of parts at the end
try:
date_str = date_str[: date_str.index("(") - 1]
except ValueError:
pass
# Then, try different date formats
for date_format in [
"%a, %d %b %Y %H:%M:%S %z",
"%a %b %d %Y %H:%M:%S %z",
"%a %b %d %H:%M:%S %Y %z",
"%d %b %Y %H:%M:%S %z",
]:
try:
return datetime.strptime(date_str, date_format)
except ValueError:
pass
raise ValueError("No valid date format found for {}".format(date_str))
In the 201201.mbox, the following error raises:
ValueError: No valid date format found for Fri, 20 Jan 2012 16:31:14 +0580
When I inspect the mbox, I realized that it includes Date: Fri, 20 Jan 2012 16:31:14 +0580 line. So, it does not match any of the date formats in the function but the problem is +0580 should be "a 5-character string of the form +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and MM is a 2-digit string giving the number of UTC offset minutes" (docs)
According to the mbox, the offset of the mail date is +0580, which means plus 5 hours and 80 minutes. Isn't that wrong? Or, do I miss something?
There are only 60 minutes in an hour, so MM can't be more than 59. +0580 should be +0620.
I've this string variable:
date_string = "17 Apr"
How can I get this: 17-04-2018?
I'm trying with this
datetime_object = datetime.strptime(date_string, "%d %B")
But I'm getting:
builtins.ValueError: time data '17 Apr' does not match format '%d %B
Thanks!
As you can see in the documentation, you should use %b (lowercase) for "Locale’s abbreviated month name". %B is for "Locale’s full month name".
import time
date_string = "17 Apr"
datetime_object = time.strptime(date_string, "%d %b")
print(datetime_object)
Pyfiddle
Using datetime module.
Ex:
import datetime
s = "17 Apr"
print(datetime.datetime.strptime("{0} 2018".format(s), "%d %b %Y").strftime("%d-%m-%Y"))
Output:
17-04-2018
Not sure why I'm getting this error when trying to parse a string into datetime.
This is the code I have:
date = datetime.strptime("13 Aug 05", '%d %m %y')
and it is raising this error:
ValueError: time data '13 Aug 05' does not match format '%d %m %y'
date = datetime.strptime("13 Aug 05", '%d %b %y')
You need to use %b, not %m, because your string uses the month's 3-letter abbreviated name and not the zero-padded decimal number.
When using
import datetime
s = 'Sat Apr 23 2016 00:00:00 GMT+0100'
print datetime.datetime.strptime(s, "%a %m %d %y %H:%M:%S GMT+0100")
I get:
ValueError: time data 'Sat Apr 23 2016 00:00:00 GMT+0100' does not match format '%a %m %d %y %H:%M:%S GMT+0100'
How to parse such a string?
Note: Using dateutil.parser.parse didn't work : it produced some weird datetime object that I could not subtract with another datetime, i.e. d1 - d2 didn't work.
According to this reference,
the format should be "%a %b %d %Y %H:%M:%S GMT+0100"
Use this format string instead: "%a %b %d %Y %H:%M:%S GMT+0100".
I made two changes:
Replaced %m (Month as a zero-padded decimal number) with %b (Month as locale’s abbreviated name)
Replaced %y (Year without century as a zero-padded decimal number) with %Y (Year with century as a decimal number)
I am using the following date format:
d.strftime("%A, %d %B %Y %H:%m")
and since the length of the weekday (%A) changes,
I would like to always print the weekday with
10 characters, pad spaces to the left, and align it right.
Something like
d.strftime("10%A, %d %B %Y %H:%m")
What is the simplest way?
str.rjust(10) does exactly that:
s = d.strftime('%A').rjust(10) + d.strftime(', %d %B %Y %H:%M')
It is likely that you want %M (minutes), not %m (months) in your format string as #Ahmad pointed out.
In Python 3.6+, to get a more concise version, one can abuse nested f-strings:
>>> f"{f'{d:%A}':>10}, {d:%d %B %Y %H:%M}"
' Friday, 15 December 2017 21:31'
Prefer standard time formats such as rfc 3339:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat() + 'Z'
'2016-02-05T14:00:43.089828Z'
Or rfc 2822:
>>> from email.utils import formatdate
>>> formatdate(usegmt=True)
'Fri, 05 Feb 2016 14:00:51 GMT'
instead.
How about this:
d.strftime("%A") + " " * (10 - len(d.strftime("%A")) + "," + d.strftime("%d %B %Y %H:%m")
Jack
This is roughly equivalent to jfs's answer, but you can use .format() to make it slightly shorter:
s = '{:>10}, {:%d %B %Y %H:%m}'.format(d.strftime('%A'), d)
or if you're putting more than just the date into the string:
args = {
'weekday' = d.strftime('%A'),
'date' = d,
'foo' = some_other_stuff(),
'bar' = 17.5422,
}
s = '{weekday:>10}, {date:%d %B %Y %H:%m} {foo} {bar:>3.2f}'.format(**args)