Python中如何将API中的ISO格式日期转换为时间戳并完成运算后转回日期格式
Hey Ben, no worries—this is a straightforward task with Python's built-in datetime module, and I'll walk you through each step clearly.
1. Convert ISO 8601 String to Unix Timestamp (Seconds)
First, we need to parse the ISO 8601 string into a datetime object, then convert it to a timestamp. The Z suffix in your date means it's in UTC timezone, so we'll handle that correctly to support all Python 3 versions:
from datetime import datetime # Your input ISO date string iso_date = "2022-06-01T10:36:56.000Z" # Parse the string (replace 'Z' with '+00:00' for broad Python compatibility) utc_dt = datetime.fromisoformat(iso_date.replace('Z', '+00:00')) # Convert to Unix timestamp (seconds since epoch, UTC) timestamp = utc_dt.timestamp() print(timestamp) # Output: 1654084616.0
If you need an integer timestamp instead of a float, just wrap it with int(timestamp).
2. Perform Arithmetic on the Timestamp
Since the timestamp is a numeric value (float or integer), you can directly do addition, division, or any other arithmetic operations like you would with regular numbers:
# Example: Add 1 hour (3600 seconds) to the timestamp updated_timestamp = timestamp + 3600 # Example: Divide the timestamp by 2 (just a demo operation) divided_timestamp = timestamp / 2
3. Convert Modified Timestamp Back to Human-Readable Format
To turn the adjusted timestamp back into a date string (like "Day/Date/Hour"), convert it back to a datetime object first (using UTC to match the original date), then use strftime() to format it to your needs:
# Convert timestamp back to UTC datetime object updated_dt = datetime.utcfromtimestamp(updated_timestamp).replace(tzinfo=datetime.timezone.utc) # Format to "Day/Date/Hour" (customize the format string as needed) formatted_date = updated_dt.strftime("%a/%Y-%m-%d/%H") print(formatted_date) # Output: Wed/2022-06-01/11
Here’s a quick breakdown of the strftime codes used:
%a: Abbreviated weekday name (e.g., "Wed")%Y: 4-digit year%m: 2-digit month%d: 2-digit day of month%H: 24-hour format hour
If you want a different layout (like full weekday name or 12-hour time), adjust the format string—for example, "%A/%d-%m-%Y/%I %p" would give you "Wednesday/01-06-2022/11 AM".
A quick note: Always stick to UTC for these conversions unless you explicitly need to work with a local timezone—this avoids unexpected offset errors.
内容的提问来源于stack exchange,提问作者Ben




