Python - Convert String date "17 Apr" to Date "17-04-2018" - python

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

Related

Python datetime strptime() does not match format

I get the following error in which you can see the time data and the format I am using
time data '20:07:35 EEDT Wed Mar 31 2021' does not match format '%H:%M:%S %Z %a %b %d %Y'
I used the directives from here and I see that the format matches the description of each directive.
Can you see what is the issue here?
import datetime
time = '20:07:35 EEDT Wed Mar 31 2021'
time = time.replace('EEDT', '+0300')
datetime.datetime.strptime(time, '%H:%M:%S %z %a %b %d %Y')
you can map the abbreviated time zone to a IANA time zone name by dateutil's parser:
import dateutil
s = '20:07:35 EEDT Wed Mar 31 2021'
tzmapping = {"EEDT": dateutil.tz.gettz('Europe/Athens'),
"EEST": dateutil.tz.gettz('Europe/Athens')} # add more if needed...
dtobj = dateutil.parser.parse(s, tzinfos=tzmapping)
that will give you
dtobj
# >>> datetime.datetime(2021, 3, 31, 20, 7, 35, tzinfo=tzfile('Europe/Athens'))
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=10800) # UTC+3
Note that timedelta arithmetic works correctly, i.e. includes DST changes:
from datetime import timedelta
dtobj -= timedelta(7) # DST change: dtobj is now EEST, UTC+2
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=7200)
Problem is with EEDT. If you ignore EEDT(quickfix, not ideal), then your code may look like:
text = '20:07:35 EEDT Wed Mar 31 2021';
fmt = '%H:%M:%S EEDT %a %b %d %Y';
datetime.strptime(text, fmt)
--edit--
parsing datetime with timezone is difficult to pure datetime module. I'm not big expert, but pytz or python-datetutil should be good choice, according to this page: https://medium.com/#nqbao/python-timezone-and-daylight-savings-e511a0093d0
For those who are interested in different approach for similar, like GMT and BST or EEST and EEDT, it can be represented like this:
import datetime
try:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S GMT %Y")
except:
Time1 = datetime.datetime.strptime(DropTm,"%a %b %d %H:%M:%S BST %Y")
In your situation it will be:
import datetime
try:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEDT %a %b %d %Y")
except:
Time1 = datetime.datetime.strptime(SomeValue,"%H:%M:%S EEST %a %b %d %Y")
Where is "SomeValue" your data!!
It did worked for me and do not need any other libraries! Good Luck with coding!!!

Parsing long string as datetime

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)

Python strftime %A fixed length

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)

Converting String to Date Format in Python

I have the following date I need to convert:
Wed, 09 Jul 2014 12:22:17 +0000
This is currently stored as a String. I wrote this code to convert it to the date format I want (the String above is passed as an argument to the covertDate function):
def convertDate(dictValue):
date_string = dictValue
format_string = '%a, %d %b %Y %H:%M:%S %z'
date_object = datetime.datetime.strptime(date_string, format_string)
date_correct_form = date_object.strftime("%Y-%m-%d")
print(type(date_correct_form))
print(date_correct_form)
return date_correct_form
The output is as follows:
<class 'str'>
2014-10-30
I get the format that I want, but it still isn't recognized as a date.
How can I make it so?
You are returning date_correct_form, which is the result of strftime:
Return a string representing the date, controlled by an explicit format string.
(emphasis mine)
If you want the datetime object, return date_object. If you need both, you can return both:
return date_correct_form, date_object
You can call it like so:
date_string, date_obj = convertDate(dictValue)
You now have the already formatted string in date_string, and if you still need to do logic against the datetime object, that is in date_obj
You can use easy_date to make it easy:
import date_converter
converted_date = date_converter.string_to_date(date_string, '%a, %d %b %Y %H:%M:%S %z')

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

Categories