How to Format Date String via Multiple Formats in Python

How to format date string via multiple formats in python

Try each format and see if it works:

from datetime import datetime

def try_parsing_date(text):
for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
try:
return datetime.strptime(text, fmt)
except ValueError:
pass
raise ValueError('no valid date format found')

Parse Date from string present in multiple formats into datetime format

dateutil's parser can help:

from dateutil import parser

for d in ["20200618", "18-june-2020"]:
print(parser.parse(d))

2020-06-18 00:00:00
2020-06-18 00:00:00

How to format multiple date formats into single date in python

In an ideal world, you know the format of your inputs.

Where this is not possible, I recommend you use a 3rd party library for mixed format dates.

Two libraries that come to mind are dateutil (via dateutil.parser.parse) and pandas (via pandas.to_datetime). Below is an example implementation with the former.

Note the only occasion when parser.parse was unsuccessful had to be covered with a manual conversion via datetime.strptime. datetime is part of the standard Python library.

from datetime import datetime
from dateutil import parser

list1 = ["30-4-1994", "1994-30-04", "30/04/1994",
"30-apr-1994", "30/apr/1994","1994-30-apr"]

def converter(lst):
for i in lst:
try:
yield parser.parse(i)
except ValueError:
try:
yield parser.parse(i, dayfirst=True)
except ValueError:
try:
yield datetime.strptime(i, '%Y-%d-%b')
except:
yield i

res = list(converter(list1))

# [datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0)]

You can then format into strings any way you like using datetime.strptime:

res_str = [i.strftime('%d-%m-%Y') for i in res]

# ['30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994']

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Convert date into format %d%m%y Python

>>> from_date="12 December 2021"
>>> import time
>>> conv=time.strptime(from_date,"%d %B %Y")
>>> time.strftime("%d/%m/%y",conv)
'121221'

>>> from_date="2021 12 December"
>>> import time
>>> conv=time.strptime(from_date,"%Y %d %B")
>>> time.strftime("%d%m%y",conv)
'121221'

Converting dates with multiple formats in a CSV file

This might work but I'm too lazy to check it against an image of a CSV file.

import pandas as pd

# Put all the formats into a list
possible_formats = ['%Y-%m-%d', '%d/%m/%Y']

# Read in the data
data = pd.read_csv("data_file.csv")
date_column = "date"

# Parse the dates in each format and stash them in a list
fixed_dates = [pd.to_datetime(data[date_column], errors='coerce', format=fmt) for fmt in possible_formats]

# Anything we could parse goes back into the CSV
data[date_column] = pd.NaT
for fixed in fixed_dates:
data.loc[~pd.isnull(fixed), date_column] = fixed[~pd.isnull(fixed)]

data.to_csv("new_file.csv")

How to convert a vector of strings in multiple formats into dates in R

Use parse_date_time from lubridate and pass multiple formats your date can take.

dates <- c("2017-12-31","2017-12-30","2017-29-12","2017-28-12")

as.Date(lubridate::parse_date_time(dates, c('ymd', 'ydm')))
#[1] "2017-12-31" "2017-12-30" "2017-12-29" "2017-12-28"

This like other answers gives preference to ymd first and if it cannot identify the date then goes and checks for ydm format.



Related Topics



Leave a reply



Submit