Python: How can I convert string to datetime without knowing the format?
super short answer:
from dateutil import parser
parser.parse("8:36pm")
>>>datetime.datetime(2015, 6, 26, 20, 36)
parser.parse("18:36")
>>>datetime.datetime(2015, 6, 26, 18, 36)
Dateutil should be available for your python installation; no need for something large like pandas
If you want to extract the time from the datetime
object:
t = parser.parse("18:36").time()
which will give you a time
object (if that's of more help to you).
Or you can extract individual fields:
dt = parser.parse("18:36")
hours = dt.hour
minute = dt.minute
How to convert String to Date without knowing the format?
You cant!
If you have the date 2010-08-05
then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.
Convert string to date object without using the format
You need to know some sort of formatting information. If you have a few ideas, you can just iterate through them.
private static String[] formats = new String[] {/* Your list of possible formats */};
public static Date parse(String date) throws ParseException {
for (String format : formats) {
DateFormat df = new SimpleDateFormat(format);
try {
return df.parse(date);
} catch (ParseException e) {}
}
throw new ParseException(
"This date does not conform to any known format", 0);
}
Of course, this is only if the same date won't fulfill multiple formats (e.g., 01/01/01 as mentioned in comments)
convert string to date without changing timezone in the string using java
Just omit the timezone format from the end of the String (letter Z
).
For example, this will print Thu Nov 12 06:30:00 CET 2020
String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
var date = format.parse(s);
System.out.println(date);
But if I add the letter Z
at the end, it will interpret the given timezone and change time to my local timezone, when printed. So this will print Thu Nov 12 15:30:00 CET 2020
String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
var date = format.parse(s);
System.out.println(date);
More about the patterns can be found in the JavaDoc of SimpleDateFormat.
Convert String to DateTime object in specific format(ex. without Date)
You could use Locale
with your DateTimeFormatter
-
String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a",Locale.ENGLISH);
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);
And also note you have to use LocalTime.parse()
here, since your string in the date doesn't contain date part.
How to convert string to date in without knowing the string format
Do you mean this ?
SELECT unix_timestamp('2013-11-14'),
unix_timestamp('2013/11/14'),
unix_timestamp('13/11/14'),
unix_timestamp('13-11-14'),
from_unixtime(unix_timestamp('13-11-14'))
This will output
1384358400 1384358400 1384358400 1384358400 "2013-11-14 00:00:00".
Java string to date conversion
That's the hard way, and those java.util.Date
setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date
class was de-facto deprecated (discommended) since introduction of java.time
API in Java 8 (2014).
Simply format the date using DateTimeFormatter
with a pattern matching the input string (the tutorial is available here).
In your specific case of "January 2, 2010" as the input string:
- "January" is the full text month, so use the
MMMM
pattern for it - "2" is the short day-of-month, so use the
d
pattern for it. - "2010" is the 4-digit year, so use the
yyyy
pattern for it.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02
Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter)
instead of LocalDate#parse(text, formatter)
. And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter)
instead.
Here's an extract of relevance from the javadoc, listing all available format patterns:
Symbol | Meaning | Presentation | Examples |
---|---|---|---|
G | era | text | AD; Anno Domini; A |
u | year | year | 2004; 04 |
y | year-of-era | year | 2004; 04 |
D | day-of-year | number | 189 |
M /L | month-of-year | number/text | 7; 07; Jul; July; J |
d | day-of-month | number | 10 |
Q /q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter |
Y | week-based-year | year | 1996; 96 |
w | week-of-week-based-year | number | 27 |
W | week-of-month | number | 4 |
E | day-of-week | text | Tue; Tuesday; T |
e /c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T |
F | week-of-month | number | 3 |
a | am-pm-of-day | text | PM |
h | clock-hour-of-am-pm (1-12) | number | 12 |
K | hour-of-am-pm (0-11) | number | 0 |
k | clock-hour-of-am-pm (1-24) | number | 0 |
H | hour-of-day (0-23) | number | 0 |
m | minute-of-hour | number | 30 |
s | second-of-minute | number | 55 |
S | fraction-of-second | fraction | 978 |
A | milli-of-day | number | 1234 |
n | nano-of-second | number | 987654321 |
N | nano-of-day | number | 1234000000 |
V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 |
z | time-zone name | zone-name | Pacific Standard Time; PST |
O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; |
X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; |
x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; |
Z | zone-offset | offset-Z | +0000; -0800; -08:00; |
Related Topics
Make Arraylist.Toarray() Return More Specific Types
Calculating All of the Subsets of a Set of Numbers
Delete Item from Array and Shrink Array
Java Equivalent of an Openssl Aes Cbc Encryption
How to Initialize Hashset Values by Construction
How to Negate a Method Reference Predicate
Working with a List of Lists in Java
Is Java 7 Using Tim Sort for the Method Arrays.Sort
Scala Equivalent of Java Java.Lang.Class<T> Object
How to Validate an Xml File Using Java with an Xsd Having an Include
Where Are Compiled Jsp Java (*_Jsp.Java) Files
How to Inject an Object into Jersey Request Context
What Does an Exclamation Mark Mean in Java
Difference Between Arrays.Aslist(Array) and New Arraylist<Integer>(Arrays.Aslist(Array))
Replacing All Non-Alphanumeric Characters with Empty Strings