Datetime not matching format - python

I'm trying to convert a string into a datetime. However is says that I don't follow the format and I am confused. Could anyone help me please?
Code:
from datetime import datetime
date = datetime.strptime('2021-11-27 00:00', '%y-%m-%d %H:%M')
Error:
ValueError: time data '2021-11-27 00:00' does not match format '%y-%m-%d %H:%M'

The %y code matches a two-digit year - for a four-digit year, you should use %Y instead.
date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M')

as per the documentation, %y is
Year without century as a zero-padded decimal number.
and %Y is
Year with century as a decimal number.
so
from datetime import datetime
date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M')
date
will give
datetime.datetime(2021, 11, 27, 0, 0)

I'm not familiar with python too much but this documentation says %y is for year without century but %Y is for year with century:
Directive
Meaning
%y
Year without century as a zero-padded decimal number.
%Y
Year with century as a decimal number.
So, looks like the correct format should be %Y-%m-%d %H:%M
Here a demonstration.
Remember, almost all programming languages have this custom specifiers and most of them are case sensitive.

Related

Convert DataFrame column from string to datetime for format "January 1, 2001 Monday"

I am trying to convert a dataframe column "date" from string to datetime. I have this format: "January 1, 2001 Monday".
I tried to use the following:
from dateutil import parser
for index,v in df['date'].items():
df['date'][index] = parser.parse(df['date'][index])
But it gives me the following error:
ValueError: Cannot set non-string value '2001-01-01 00:00:00' into a StringArray.
I checked the datatype of the column "date" and it tells me string type.
This is the snippet of the dataframe:
Any help would be most appreciated!
why don't you try this instead of dateutils, pandas offer much simpler tools such as pd.to_datetime function:
df['date'] = pd.to_datetime(df['date'], format='%B %d, %Y %A')
You need to specify the format for the datetime object in order it to be parsed correctly. The documentation helps with this:
%A is for Weekday as locale’s full name, e.g., Monday
%B is for Month as locale’s full name, e.g., January
%d is for Day of the month as a zero-padded decimal number.
%Y is for Year with century as a decimal number, e.g., 2021.
Combining all of them we have the following function:
from datetime import datetime
def mdy_to_ymd(d):
return datetime.strptime(d, '%B %d, %Y %A').strftime('%Y-%m-%d')
print(mdy_to_ymd('January 1, 2021 Monday'))
> 2021-01-01
One more thing is for your case, .apply() will work faster, thus the code is:
df['date'] = df['date'].apply(lambda x: mdy_to_ymd)
Feel free to add Hour-Minute-Second if needed.

How can I change this format to be datetime format? (python)

I have a dataset which contains some columns with datetime. My problem is, I found this type datetime format:
Apr'11
Apr-11
Apr 11
How can I automatically change this format to be datetime format?
for you can use datetime module
from datetime import datetime
this is the link if you want any confusion
date_string = "Apr'11"
date = datetime.strptime(date_string, "%b'%d")
%b = Locale’s abbreviated month name. (like Apr, Mar, Jan, etc)
%d = Day of the month as a decimal number [01,31]
date_string_2 = "Apr-11"
date = datetime.strptime(date_string, "%b-%d")
date_string_3 = "Apr 11"
date = datetime.strptime(date_string, "%b %d")
You should write this "%b %d" same as like date_string otherwise it will give you, even if you give an extra space.
go to this link to learn more about this:
https://docs.python.org/3/library/time.html

Converting 1OCT20 to Datetime

I have a series of dates but in a format like "1OCT20" or "30MAR19", how can I convert them into datetime?
thanks in advance
use pd.to_datetime with the format argument set to %d%b%y
%d Day of the month as a zero-padded decimal number.
%b Month as locale’s abbreviated name.
%y Year without century as a zero-padded decimal number.
I usually use this https://strftime.org/ website when looking for specific datetime formats.
pd.to_datetime('1OCT20',format='%d%b%y')
Timestamp('2020-10-01 00:00:00')
pd.to_datetime('30MAR19',format='%d%b%y')
Timestamp('2019-03-30 00:00:00')
on your dataset you can cast it directly on your column
df['trgdate'] = pd.to_datetime(df['srcdate'],format='%d%b%y')

convert string date to another string date

from datetime import datetime
y='Monday, December 9, 2019'
I want to convert the above string to DD/MM/YYYY I tried
c=datetime.strptime(y,'%A, %B %-d,%Y')
so I can then easily convert it but it is giving me ValueError: '-' is a bad directive in format '%A, %B %-d,%Y I checked this question
'-' is a bad directive in format '%Y-%-m-%-d' - python/django but still gives error, is there a way to do this without using re ?
The correct format is '%A, %B %d, %Y' (noticed the removed -), and to change it to DD/MM/YYYY, the format is %d-%m-%Y'
from datetime import datetime
y='Monday, December 9, 2019'
#Fixed format
c=datetime.strptime(y,'%A, %B %d, %Y')
#Changed to represent DD/MM/YYYY
print(c.strftime('%d-%m-%Y'))
The output will be
09-12-2019

Format Unicode time value

I have next time value in unicode (<type 'unicode'>):
2017-08-09T15:02:58+0000.
How to convert it to friendly view (e.g. Day, Month of Year)?
This should do what you ask:
from datetime import datetime
a = '2017-08-09T15:02:58+0000'
datetime.strptime(a[:-5], '%Y-%m-%dT%H:%M:%S').strftime('%d, %b of %Y')
#09, Aug of 2017
strptime method throws error for timezone parameter that doesn't seem to interest you so I removed that part with a[:-5].
For the rest of the string you can just follow guidelines from datetime docs.
Using the same docs you can construct your datetime string using strftime() method like you wanted '%d, %b of %Y' or in plain words [day], [abbreviated month] of [Year]
try this
import datetime
today = datetime.date.today()
print today.strftime('We are the %d, %b %Y')
'We are the 22, Nov 2008'

Categories

Resources