Last active
August 6, 2023 06:15
-
-
Save manojjha/bfe681736dbaa97312f21b9612266525 to your computer and use it in GitHub Desktop.
How to Convert String Dates to Date Format in Python and C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.DateTime; | |
using System.Text.RegularExpressions; | |
public class DateConverter | |
{ | |
public static DateTime ConvertStringToDate(string stringDate) | |
{ | |
// The regular expression to match a date string with month in word. | |
string regex = @"^\d{4}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{1,2}$"; | |
// The format of the string date. | |
string date_format = "yyyy-MM-dd"; | |
// Convert the string date to a DateTime object. | |
DateTime date = DateTime.Parse(stringDate, date_format); | |
return date; | |
} | |
public static void Main() | |
{ | |
// The string dates to convert. | |
string[] stringDates = { | |
"2023-08-05", | |
"05-Aug-2023", | |
"Aug/05/2023", | |
"5/Aug/2023", | |
}; | |
// Iterate over the string dates and convert them to DateTime objects. | |
for (string stringDate in stringDates) | |
{ | |
date = ConvertStringToDate(stringDate); | |
// Print the DateTime object. | |
Console.WriteLine(date); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import re | |
def convert_string_date_to_date(string_date): | |
"""Converts a string date to a date format. | |
Args: | |
string_date: The string date to convert. | |
Returns: | |
A date object. | |
""" | |
date_formats = [ | |
"%Y-%m-%d", | |
"%d-%b-%Y", | |
"%b/%d/%Y", | |
"%d/%b/%Y", | |
] | |
for date_format in date_formats: | |
try: | |
date = datetime.datetime.strptime(string_date, date_format) | |
return date | |
except ValueError: | |
pass | |
raise ValueError("Unable to convert string date to date format") | |
if __name__ == "__main__": | |
string_dates = [ | |
"2023-08-05", | |
"05-Aug-2023", | |
"Aug/05/2023", | |
"5/Aug/2023", | |
] | |
for string_date in string_dates: | |
date = convert_string_date_to_date(string_date) | |
print(date) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment