杰瑞科技汇

python todatetime

Of course! In Python, the term "to datetime" most commonly refers to converting other data types (like strings, numbers, or timestamps) into a Python datetime object.

python todatetime-图1
(图片来源网络,侵删)

The primary tool for this is the datetime module from the Python standard library. The most flexible and powerful function within it for this task is datetime.strptime().

Let's break down the different ways to convert to a datetime object.


The Main Tool: datetime.strptime()

strptime stands for "string parse time". It takes a string representing a date/time and a format code, then parses the string into a datetime object.

Syntax

from datetime import datetime
datetime_object = datetime.strptime(date_string, format_code)

Format Codes

These codes tell strptime how to interpret the characters in your string. Here are the most common ones:

python todatetime-图2
(图片来源网络,侵删)
Code Meaning Example
%Y Year with century 2025
%y Year without century 23
%m Month as a zero-padded number 05 (for May)
%B Full month name May
%b Abbreviated month name May
%d Day of the month 25
%H Hour (24-hour clock) 14 (for 2 PM)
%I Hour (12-hour clock) 02 (for 2 PM)
%M Minute 30
%S Second 05
%p Locale’s AM or PM PM

Examples of strptime

Example 1: Standard Format (YYYY-MM-DD)

This is a very common format.

from datetime import datetime
date_string = "2025-10-27"
format_code = "%Y-%m-%d"
dt_object = datetime.strptime(date_string, format_code)
print(f"Original String: {date_string}")
print(f"Datetime Object: {dt_object}")
print(f"Type: {type(dt_object)}")
# Output:
# Original String: 2025-10-27
# Datetime Object: 2025-10-27 00:00:00
# Type: <class 'datetime.datetime'>

Example 2: With Time and AM/PM

Here we combine date and time elements.

from datetime import datetime
datetime_string = "27-Oct-2025 02:30:00 PM"
format_code = "%d-%b-%Y %I:%M:%S %p"
dt_object = datetime.strptime(datetime_string, format_code)
print(f"Original String: {datetime_string}")
print(f"Datetime Object: {dt_object}")
# Output:
# Original String: 27-Oct-2025 02:30:00 PM
# Datetime Object: 2025-10-27 14:30:00

Example 3: Handling Different String Formats

You must match the format code to the string exactly, including separators.

# String with slashes
date_string_slash = "10/27/23"
format_code_slash = "%m/%d/%y"
dt_slash = datetime.strptime(date_string_slash, format_code_slash)
print(f"Slash format: {dt_slash}") # Output: 2025-10-27 00:00:00
# String with full month name
date_string_month = "October 27, 2025"
format_code_month = "%B %d, %Y"
dt_month = datetime.strptime(date_string_month, format_code_month)
print(f"Month name format: {dt_month}") # Output: 2025-10-27 00:00:00

Converting Other Data Types to datetime

While strptime is for strings, you often need to convert other types.

python todatetime-图3
(图片来源网络,侵删)

From a Unix Timestamp

A Unix timestamp is the number of seconds since January 1, 1970. Use datetime.fromtimestamp().

from datetime import datetime
# Timestamp for October 27, 2025, 14:30:00 UTC
timestamp = 1698388200
dt_object = datetime.fromtimestamp(timestamp)
print(f"Timestamp: {timestamp}")
print(f"Datetime Object: {dt_object}")
# Output:
# Timestamp: 1698388200
# Datetime Object: 2025-10-27 14:30:00

From an Integer (YYYYMMDD)

You can't use strptime directly for this. The best way is to convert the integer to a string first.

from datetime import datetime
int_date = 20251027
# Convert to string and then use strptime
date_string = str(int_date)
format_code = "%Y%m%d"
dt_object = datetime.strptime(date_string, format_code)
print(f"Integer: {int_date}")
print(f"Datetime Object: {dt_object}")
# Output:
# Integer: 20251027
# Datetime Object: 2025-10-27 00:00:00

Handling User Input: The dateutil Module

The strptime function can be strict and will raise a ValueError if the format doesn't match perfectly. This can be frustrating when dealing with unpredictable user input or data from different sources.

A much more flexible alternative is the dateutil library, which can often guess the correct format.

First, you need to install it:

pip install python-dateutil

Example: dateutil.parser

dateutil.parser.parse() is very powerful.

from dateutil import parser
# It can handle many different formats automatically
date_string1 = "2025-10-27"
date_string2 = "27/10/2025"
date_string3 = "Oct 27, 2025"
date_string4 = "October 27, 2025 14:30"
dt1 = parser.parse(date_string1)
dt2 = parser.parse(date_string2)
dt3 = parser.parse(date_string3)
dt4 = parser.parse(date_string4)
print(f"Parsed: {dt1}")
print(f"Parsed: {dt2}")
print(f"Parsed: {dt3}")
print(f"Parsed: {dt4}")
# Output:
# Parsed: 2025-10-27 00:00:00
# Parsed: 2025-10-27 00:00:00
# Parsed: 2025-10-27 00:00:00
# Parsed: 2025-10-27 14:30:00

Warning: This flexibility is powerful but can be ambiguous. For example, parser.parse("01/02/03") could be interpreted as January 2nd or February 1st, depending on your locale. Use it when you need flexibility, but prefer explicit strptime formats for data you control.


Summary: Which Method to Use?

Your Input Type Recommended Method Why?
A string with a known, consistent format datetime.strptime(string, format_code) Fast, reliable, and explicit. No external dependencies.
A Unix timestamp (integer/float) datetime.fromtimestamp(timestamp) The standard, correct way to handle timestamps.
Unpredictable strings or user input dateutil.parser.parse(string) Very flexible and forgiving. Great for messy data. (Requires pip)
Integer in YYYYMMDD format datetime.strptime(str(integer), "%Y%m%d") Convert to string first, then use strptime.
A list of date strings Use a list comprehension with strptime or parse Efficiently apply the conversion to each item in the list.
分享:
扫描分享到社交APP
上一篇
下一篇