How to parse a string into a datetime object in Python
The most common method of parsing strings into datetime objects in Python is to use the strptime() function of the datetime module. This method requires writing matching format strings according to the format of the input string; common formats include %Y (four-bit year), %m (two-digit month), %d (two-digit date), %H (hour), %M (minute), %S (seconds), etc.; for non-standard formats or time strings with time zones, the format should be adjusted to match, such as %B (full month name), %I (12-hour hours), %p (AM/PM identification), and %z (time zone offset); if you want to automatically identify the format, you can use the parser.parse() method of dateutil, but pay attention to automatically identifying possible ambiguity problems.
The most common way to parse strings as datetime objects in Python is to use strptime()
method in the datetime
module. It allows you to convert a string into a datetime object according to the specified format.

Use datetime.strptime()
basic method
The basic usage of this method is:
from datetime import datetime date_string = "2023-10-05 14:30:00" date_format = "%Y-%m-%d %H:%M:%S" dt = datetime.strptime(date_string, date_format)
The key here is that the format string must exactly match the input string . For example, %Y
represents a four-digit year, %m
is a two-digit month, %d
is a two-digit date, etc.

A brief description of common formatters:
-
%Y
: Four-digit year (such as 2023) -
%m
: Double-digit month (01 to 12) -
%d
: Date of double digits (01 to 31) -
%H
: 24-hour hours (00 to 23) -
%M
: Minutes (00 to 59) -
%S
: seconds (00 to 59)
Process time strings with different formats or time zones
Some time strings may contain time zone information or have a less standard format, for example:

"October 05, 2023 at 02:30 PM" "2023/10/05 14:30:00 0800"
At this time, you need to adjust the format string to match these situations:
datetime.strptime("October 05, 2023 at 02:30 PM", "%B %d, %Y at %I:%M %p") datetime.strptime("2023/10/05 14:30:00 0800", "%Y/%m/%d %H:%M:%S %z")
Notice:
-
%B
is the full month name (such as October) -
%I
is a 12-hour hour system -
%p
is AM/PM logo -
%z
can handle time zone offsets (such as 0800)
If there is no time zone information in the string but you want to add it, you can set it manually with a third-party library such as pytz or zoneinfo.
Simplify operations with third-party libraries (optional)
If you often work with time strings in various formats, consider using a library like dateutil
, which automatically recognizes most common formats without manually writing format strings:
from dateutil import parser dt = parser.parse("2023-10-05T14:30:00 08:00")
This is very convenient for non-standardized inputs, but it also has some risks - automatic identification can cause errors, especially when dealing with fuzzy formats (such as "01/02/03").
Basically that's it. Just remember that the format string must be strictly consistent with the input, or use smarter parsing tools when you are uncertain about the format.
The above is the detailed content of How to parse a string into a datetime object in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use httpx.AsyncClient to efficiently initiate asynchronous HTTP requests. 1. Basic GET requests manage clients through asyncwith and use awaitclient.get to initiate non-blocking requests; 2. Combining asyncio.gather to combine with asyncio.gather can significantly improve performance, and the total time is equal to the slowest request; 3. Support custom headers, authentication, base_url and timeout settings; 4. Can send POST requests and carry JSON data; 5. Pay attention to avoid mixing synchronous asynchronous code. Proxy support needs to pay attention to back-end compatibility, which is suitable for crawlers or API aggregation and other scenarios.

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,
