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"
Python - convert string type to datetime type
If you work with Python 3.7+, for ISO 8601 compatible strings, use datetime.fromisoformat()
as this is considerably more efficient than strptime
or dateutil's parser
. Ex:
from datetime import datetime
dtobj = datetime.fromisoformat('2020-05-20 13:01:30')
print(repr(dtobj))
# datetime.datetime(2020, 5, 20, 13, 1, 30)
You can find a benchmark vs. strptime
etc. here or here.
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)
How to convert string time to datetime
This works but idk if thats a good way.
import datetime
def year_to_date(year):
asdate = datetime.datetime.strptime(year, '%Y')
print(asdate.date())
def month_year_to_date(month_year):
asdate = datetime.datetime.strptime(month_year, '%B %Y')
print(asdate.date())
year_to_date("1967")
month_year_to_date("May 1967")
https://stackabuse.com/converting-strings-to-datetime-in-python/
makes a good explanation to this.
BigQuery: cast string as datetime
That might be ISO 8601 format, you can use PARSE_TIMESTAMP
function.
SELECT
PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*SZ', timestamp)
FROM
`bigquery_table`
LIMIT
1000
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')
Python: How to convert string into datetime
Use the datetime.strptime
method:
import datetime
datetime.datetime.strptime(your_string, "%Y-%m-%dT%H:%M:%S.%f")
The link provided presents the different format directives. Note that the microseconds are limited to the range [0,999999]
, meaning that a ValueError
will be raised with your example (you're using 1/10us): you need to truncate your string to drop the final character.
vb.net How do I parse from String to DateTime
You are trying to cast a String object directly into a DateTime object, which is impossible to do directly as they do not share a class hierarchy that would allow them to do so.
You should try parsing the String into a DateTime object and give the parser a date format in which to process the string.
e.g.
5/7/19 in en-UK is the 5th of July 2019, in en-US it is the 7th May 2019
DateTime.Parse(MyString, MyCultureInfo)
Where your MyCultureInfo matches the format of the date string you expect to get in.
e.g.
MyCultureInfo = new CultureInfo("en-US")
ref https://learn.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime
Convert String Column directly to Date format (not Datetime) in Pandas DataFrame
pandas.DataFrame.apply
is essentially a native python for
loop.
pandas.to_datetime
is a vectorized function, meaning it's meant to operate on sequences/lists/arrays/series by doing the inner loop in C
If we start with a larger dataframe:
import pandas
df = pandas.DataFrame({'a': ['2020-01-02', '2020-01-02'] * 5000})
And then do (in a jupyter notebook)
%%timeit
df['a'].apply(pandas.to_datetime).dt.date
We get a pretty slow result:
1.03 s ± 48.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
But if we rearrange just slightly to pass the entire column:
%%timeit
pandas.to_datetime(df['a']).dt.date
We get a much faster result:
6.07 ms ± 232 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Related Topics
Count Unique Combinations of Values
How to Get the Min/Max Possible Numeric
How to Print a Variable Inside a for Loop to the Console in Real Time as the Loop Is Running
Extract Certain Files from .Zip
Rolling Join Grouped by a Second Variable in Data.Table
How to Find the Package Name in R for a Specific Function
R How to Remove Rows in a Data Frame Based on the First Character of a Column
How to Remove Leading "0." in a Numeric R Variable
Using R to Do a Regression with Multiple Dependent and Multiple Independent Variables
How to Add Legend to Geom_Smooth in Ggplot in R
How to Replace Certain Values in a Specific Rows and Columns with Na in R
R: Adding a "Tool Tip" to Interactive Plot (Plotly)
How to Retrieve the Client's Current Time and Time Zone When Using Shiny