How can I parse a DateTime from a string containing extra characters?
Both C# and JavaScript support regular expressions. You can use this pattern to find that section of the string:
\d{2}/\d{2}/\d{4}
Of course that doesn't ensure that it's a valid date, e.g. 13/88/0000
would match that pattern. You'd then have to parse the string using something like Date.Parse
.
However, since you've stated regular expressions are not an option, here's a very crude one-liner:
var input = "Hello I am a Coder, My DOB is 12/09/2011.";
DateTime date = new DateTime();
input.Split().SkipWhile(s => !DateTime.TryParse(s, out date)).Any();
Console.WriteLine(date); // 12/9/2011 12:00:00 AM
How do I parse date-time strings with various characters as date delimiters?
Be very careful with ambiguous formats. If one device returns yyyy/MM/dd
and the other returns yyyy/dd/MM
you might find yourself returning wrong results.
I would recommend TryParseExact
instead of ParseExact
in a try..catch block.
The overload I've linked to can take an array of strings as possible formats, and will parse successfully if the input string matches exactly (at least) one of them.
var formats = new string[]
{
"yyyy:MM:dd HH:mm:ss",
"yyyy/MM/dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss"
};
DateTime dt;
if(
DateTime.TryParseExact(
str,
formats,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, // Please note AssumeLocal might be wrong here...
out dt)
) // parsed successfully...
Python how to convert string with special character into datetime
Your format string is incorrect.
>>> datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 7, 7, 2, 27, tzinfo=datetime.timezone.utc)
Java DateTimeFormatter parsing with special characters
Your only problem is that the -4
in your string needs a leading zero, as @deHaar indicated in his comment, i.e.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss.SSS'['x':'z']'");
LocalDateTime ldt = LocalDateTime.parse("20200915095318.883[-04:EDT]", formatter);
Convert a large character string to dates, but the dates have a non numeric character
You can use :
dates_MODIS <- c("X2015.01.01", "X2015.01.17", "X2015.02.02")
dates_MODIS <- as.Date(dates_MODIS, 'X%Y.%m.%d')
dates_MODIS
#[1] "2015-01-01" "2015-01-17" "2015-02-02"
Java date format - including additional characters
Sure, with the SimpleDateFormat you can include literal strings:
Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
Parse date string and change format
datetime
module could help you with that:
datetime.datetime.strptime(date_string, format1).strftime(format2)
For the specific example you could do
>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
Parse String to Date with Different Format in Java
Take a look at SimpleDateFormat
. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
Related Topics
Azure Put Blob Authentication Fails in R
Evaluate (I.E., Predict) a Smoothing Spline Outside R
Dplyr Summarise_Each with Na.Rm
Get Selected Row from Datatable in Shiny App
Extract Text from Two-Column PDF with R
Gbm R Function: Get Variable Importance Separately for Each Class
Display an Axis Value in Millions in Ggplot
Writing R Function with If Enviornment
Bookmarking and Saving the Bookmarks in R Shiny
Plotting the Average Values for Each Level in Ggplot2
How to Preserve Transparency in Ggplot2
Really Fast Word Ngram Vectorization in R
Non-Linear Color Distribution Over the Range of Values in a Geom_Raster