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 3strptime
/strftime
format string docs: Python 2, Python 3strftime.org format string cheatsheet
Notes:
strptime
= "string parse time"strftime
= "string format time"
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
Converting string to Date and DateTime
Use strtotime()
on your first date then date('Y-m-d')
to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash /
and hyphen -
in the strtotime()
function. To quote from php.net:
Dates in the m/d/y or d-m-y formats
are disambiguated by looking at the
separator between the various
components: if the separator is a
slash (/), then the American m/d/y is
assumed; whereas if the separator is a
dash (-) or a dot (.), then the
European d-m-y format is assumed.To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Convert date string format to a datetime Python Object
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Convert String datetime to Date in java?
Reason is you are using wrong format,here Z represents timezone
String s = "2013-09-29T18:46:19-0700";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
If time format is in above ,it will work fine.
If you just mark Z in single quotes,it will just consider as a String rather than parsing it.
Edit:-
If you want to use "2015-12-03T15:00:08.8689870",then pattern must be yyyy-MM-dd'T'HH:mm:ss.SSS
String s = "2015-12-03T15:00:08.8689870";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
If date time is in 2015-12-03T17:00:08Z,then you can use pattern yyyy-MM-dd'T'HH:mm:ssX where X denotes ISO 8601 time zone.The Java 7 version of SimpleDateFormat supports ISO-8601 time zones using the uppercase letter X.
String s = "2015-12-03T17:00:08Z";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date dtIn = inFormat.parse(s);
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
If you're stuck with Java 6 or earlier, the answer recommending JodaTime is a safe bet.
String timestamp = "2011-04-15T20:08:18Z";
DateTime dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(timestamp);
This correctly recognizes the UTC timezone and allows you to then use Joda Time's extensive manipulation methods to get what you want out of it.
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
Python date string to date object
You can use strptime
in the datetime
package of Python:
>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)
Convert string into Date type on Python
You can do that with datetime.strptime()
Example:
>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5
You can find the table with all the strptime
directive here.
To increment by 2 days if .isweekday() == 6
, you can use timedelta()
:
>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
... date += datetime.timedelta(days=2)
...
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d') # if you want a string again
'2012-02-13'
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>
Related Topics
How to Convert Json String to Array
PHP Display Image Blob from MySQL
Detecting Request Type in PHP (Get, Post, Put or Delete)
Getting Raw SQL Query String from Pdo Prepared Statements
Passing Base64 Encoded Strings in Url
How to Find Where I Will Be Redirected Using Curl in PHP
Warning: a Non-Numeric Value Encountered
Strange Behavior of Foreach When Using Reference: Foreach ($A as &$V) { ... }
How to Filter an Array by a Condition
Prevent Direct Access to a PHP Include File
How to Find the Last Day of the Month from Date
MySQL - This Version of MySQL Doesn't Yet Support 'Limit & In/All/Any/Some Subquery