need inputs to change the date pattern using python regsub - python

I am using the below reg.sub to change the date format from yyy-mm-dd to dd-mm-yyy . But the new date format also comes in the original format and does not change.Can you please point me what I am missing here?
def dateextract1(dt):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})/', '\\3-\\2-\\1', dt)
dt1 = "2026-01-02"
print("Original date in YYY-MM-DD Format: ",dt1)
print("New date in DD-MM-YYYY Format: ",dateextract1(dt1))
=======================
Original date in YYY-MM-DD Format: 2026-01-02
New date in DD-MM-YYYY Format: 2026-01-02 [ I would expect : 02-01-2026]

Any reason for using RegEx for this? The Python datetime library has a pretty effective date formatter.

Related

Python -Pandas _ Datetime conversion to a specific format such as DD-MM-YYYY

I have column emp_date which consists of different date formats such as mm/dd/yyy, mm-dd-yyyy and also dd-mm-yyyy ,along with blank spaces, and some with timestamps.And the data type is Object for this column.
I want to convert these dates into the specific format such as DD-MM-YYYY .
Since it has multiple formats and blank spaces along with my specific format i am getting different errors.
Input file: CSV file
emp_date Column
10-07-2013
1/15/2012
Blank space or Null value
1/15/2023
12/13/2021
1-15-2021
Blank space or Null value
5/31/2013
Blank space or Null value
209-06-13 00:00:00
Code:
col='Previous Employment Start Date'
CorePreviousWorkexp_bkp['col'] = pd.to_datetime(CorePreviousWorkexp_bkp[col], format='%d-%m-%Y')
or
import datetime
def format(val):
a = pd.to_datetime(val, errors='coerce', cache=False).strftime('%m/%d/%Y')
try:
date_time_obj = datetime.datetime.strptime(a, '%d/%m/%Y')
except:
date_time_obj = datetime.datetime.strptime(a, '%m/%d/%Y')
return date_time_obj.date()
Output : But multiple errors due to different formats and blank spaces.
Expected Format: DD-MM-YYYY
How to achieve this format ?
Usually pd.to_datetime does a pretty good job with differently formatted dates.
I would try a pd.to_datetime(df[col]), and DO NOT specify the format you are looking for. This will allow the function to consider multiple date formats.
After this you can df[col].fillna(somedate)
and then reformat your df[col] as you please.
EDIT: to include #FObersteiner comment below, for dates which the mm and dd could be confused, you would likely need to parse these out yourself. For example 1/5/2020 vs 5/1/2020. Only you would know which is correct.

Change date format of these string using Python

I have a string from a pdf that I want to transform it to the date format that I want to work with later,
the string is
05Dec22
how can I change it to 12/05/2022?
import datetime
date1 = '05Dec22'
date1 = datetime.datetime.strptime(date1, '%d%m%Y').strftime('%m/%d/%y')
date1 = str(date1)
This is what i tried so far
If you execute the code you'll get the following error,
ValueError: time data '05Dec22' does not match format '%d%m%Y'
this is because your time string is not in the specified format given ('%d%m%Y'). You can search for tables on the internet which show the placeholders that represent a certain formatting, if you look at the one provided here, you'll see that the formatting your string has is '%d%b%y', in this case, the %b placeholder represents the abbreviated month name and the %y placeholder is the year without century, just as your example string. Now, if you fix that in your code,
import datetime
date1 = '05Dec22'
date1 = datetime.datetime.strptime(date1, '%d%b%y').strftime('%m/%d/%Y')
date1 = str(date1)
you'll get the desired result.
Note that you also have to change the output format in strftime. As I said before, the %y placeholder is the year without century. For you to get the year including the century, you have to use %Y.

Convert string of dd-MON-yy to date in Python

I have a string in dd-MON-yy format. While converting to date in python, its is causing issue since the year is in tow digits.
datetime.datetime.strptime('17-JUN-03', '%d-%m-%y')
The error is,
ValueError: time data '17-JUN-03' does not match format '%d-%m-%y'
Try this:
import datetime
print(datetime.datetime.strptime('17-JUN-03', '%d-%b-%y'))
Result:
2003-06-17 00:00:00
Datetime format codes

How do I format date using pandas?

My data 'df' shows data 'Date' as 1970-01-01 00:00:00.019990103 when this is formatted to date_to using pandas. How do I show the date as 01/03/1999?
consider LoneWanderer's comment for next time and show some of the code that you have tried.
I would try this:
from datetime import datetime
now = datetime.now()
print(now.strftime('%d/%m/%Y'))
You can print now to see that is in the same format that you have and after that is formatted to the format required.
I see that the actual date is in last 10 chars of your source string.
To convert such strings to a Timestamp (ignoring the starting part), run:
df.Date = df.Date.apply(lambda src: pd.to_datetime(src[-8:]))
It is worth to consider to keep this date just as Timestamp, as it
simplifies operations on date / time and apply your formatting only in printouts.
But if you want to have this date as a string in "your" format, in the
"original" column, perform the second conversion (Timestamp to string):
df.Date = df.Date.dt.strftime('%m/%d/%Y')

python parse string in date format to get the date

There is a string and a date format. I want to get the date based on format.
If date format is YYYY.MM.dd and string is 2017.01.01. It should transform to a valid date object.
How can I find the date.
You can use datetime module something like this :
from datetime import datetime
date_object = datetime.strptime('2017.01.01', '%Y.%m.%d') # Converting the given date string into a datetime object.
formatted_date = date_object.strftime('%c') #User Defined Output Format
print(formatted_date)
This will result in :
Sun Jan 1 00:00:00 2017
You can refer to the documentation here.

Categories