Convert String to Datetime

Convert string Jun 1 2005 1:33PM into datetime

datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:

>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)

To obtain a date object using an existing datetime object, convert it using .date():

>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)

Links:

  • strptime docs: Python 2, Python 3

  • strptime/strftime format string docs: Python 2, Python 3

  • strftime.org format string cheatsheet

Notes:

  • strptime = "string parse time"
  • strftime = "string format time"

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object

In [56]:
df['I_DATE'].dt.time

Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

Java Convert String and Long to DateTime

java.time

Quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;

LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);

Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);

OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);

odt = odt.with(time);
System.out.println(odt);
}
}

Output:

12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Just for the sake of completeness

Just for the sake of completeness, given below is the solution using the Joda Date-Time API:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;

public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;

LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);

DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);

dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}

Output:

12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How do I convert a date/time string to a DateTime object in Dart?

DateTime has a parse method

var parsedDate = DateTime.parse('1974-03-20 00:00:00.000');

https://api.dartlang.org/stable/dart-core/DateTime/parse.html

Convert string to datetime in SQL, when Z and T literals are involved

DATETIME and SMALLDATE are legacy types(as in replaced-15-years-ago, don't-use legacy) that have a lot of quirks and limited precision. For example, datetime is only accurate to 0, 3 or 7 milliseconds. The value you tried to parse can't be converted to a datetime without losing precision.

The docs warn strongly against using this type, with a big pink warning at the top of the DATETIME page:

Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.

In this case you need the datetime2 or datetimeoffset types introduced in 2005. Both types allow specifying a precision.

To preserve the timezone offset, use datetimeoffset.

select CONVERT(datetimeoffset, '2021-12-15T14:18:22.6496978Z', 127)
----
2021-12-15 14:18:22.6496978 +00:00

To remove the offset, use datetime2. The result will have no assumed offset so you should take care to always treat it as UTC:

select CONVERT(datetimeoffset, '2021-12-15T14:18:22.6496978Z', 127)
----
2021-12-15 14:18:22.6496978

In both cases you can specify the desired precision. For example, datetime2(0) will truncate fractional seconds:

select CONVERT(datetime2(0), '2021-12-15T14:18:22.6496978Z', 127)
---
2021-12-15 14:18:23

Convert string to datetime

For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date. It may bite you, because of browser compatibility problems.

tryParseDateFromString is ES6 utility method to parse a date string using a format string parameter (format) to inform the method about the position of date/month/year in the input string. The date is constructed using Date.UTC, circumventing the aforementioned browser compatibility problems.

See also

// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
const dt = dateString.split(/\-|\s/);
return new Date(dt.slice(0, 3).reverse().join('-') + ' ' + dt[3]);
}

// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
const candidate = (dateStringCandidateValue || ``)
.split(/[ :\-\/]/g).map(Number).filter(v => !isNaN(v));
const toDate = () => {
format = [...format].reduce((acc, val, i) => ({ ...acc, [val]: i }), {});
const parts =
[candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
.concat(candidate.length > 3 ? candidate.slice(3) : []);
const checkDate = d => d.getDate &&
![d.getFullYear(), d.getMonth(), d.getDate()]
.find( (v, i) => v !== parts[i] ) && d || undefined;

return checkDate( new Date(Date.UTC(...parts)) );
};

return candidate.length < 3 ? undefined : toDate();
}

const result = document.querySelector('#result');

result.textContent =
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
dateString2Date('01-01-2016 00:03:44')}`;

result.textContent +=
`\n\n*With formatting dmy
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;

result.textContent +=
`\n\n*With formatting mdy
tryParseDateFromString('03/01/1943', 'mdy'):\n => ${
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;

result.textContent +=
`\n\n*With invalid format
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;


result.textContent +=
`\n\n*With formatting invalid string
tryParseDateFromString('03/01/null', 'mdy'):\n => ${
tryParseDateFromString('03/01/null', "mdy")}`;

result.textContent +=
`\n\n*With formatting no parameters
tryParseDateFromString():\n => ${tryParseDateFromString()}`;
<pre id="result"></pre>

How to convert string to datetime?

Here to parse a string to date time, then you can:

def convert(s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')

someobject = convert('2017-08-15T13:34:35Z')
print(someobject.isoformat())

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')


Related Topics



Leave a reply



Submit