如何自行实现Unix时间戳转datetime?Python下不依赖fromtimestamp的方法
datetime.fromtimestamp() in Python) Great question! Let's start with the basics, then build our own conversion function from scratch.
First, a quick recap: A Unix timestamp is the number of seconds (sometimes milliseconds, watch out!) that have elapsed since the Unix Epoch: January 1st, 1970 00:00:00 UTC. The core of manual conversion is breaking down that total number of seconds into years, months, days, hours, minutes, and seconds, starting from the epoch.
Step 1: Understand the Rules We Need to Follow
- Leap Years: A year is a leap year if it's divisible by 4, but not by 100 unless it's also divisible by 400. Leap years have 366 days (February has 29 days instead of 28).
- Month Days: Each month has a fixed number of days, except February which depends on leap years.
- Time Units: 1 hour = 3600 seconds, 1 minute = 60 seconds, 1 day = 86400 seconds.
Step 2: Build the Custom Conversion Function
Let's code this step by step in Python. First, we'll write a helper function to check for leap years, then the main conversion function.
Helper Function: Check for Leap Years
def is_leap_year(year): # Leap year rules: divisible by 4, not by 100 unless also by 400 if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True return False
Main Function: Convert Timestamp to Datetime
def timestamp_to_datetime(timestamp): # Start with the Unix Epoch values year = 1970 month = 1 day = 1 hour = 0 minute = 0 second = 0 # Total seconds we need to distribute remaining_seconds = timestamp # First, handle full years while True: days_in_year = 366 if is_leap_year(year) else 365 seconds_in_year = days_in_year * 86400 # 86400 sec/day if remaining_seconds < seconds_in_year: break remaining_seconds -= seconds_in_year year += 1 # Next, handle full months # Days per month (index 0 is dummy for 1-based month numbering) month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap_year(year): month_days[2] = 29 # Update February for leap year while True: seconds_in_month = month_days[month] * 86400 if remaining_seconds < seconds_in_month: break remaining_seconds -= seconds_in_month month += 1 # Now handle days days = remaining_seconds // 86400 day += days remaining_seconds -= days * 86400 # Then hours hour = remaining_seconds // 3600 remaining_seconds -= hour * 3600 # Then minutes minute = remaining_seconds // 60 second = remaining_seconds % 60 # Return a tuple or formatted string (adjust as needed) return (year, month, day, hour, minute, second)
Step 3: Test the Function
Let's test with a known timestamp to verify:
- Timestamp
1609459200corresponds to 2021-01-01 00:00:00 UTC
print(timestamp_to_datetime(1609459200)) # Output: (2021, 1, 1, 0, 0, 0) ✅
Another test: Timestamp 1717209600 is 2024-06-01 00:00:00 UTC (2024 is a leap year)
print(timestamp_to_datetime(1717209600)) # Output: (2024, 6, 1, 0, 0, 0) ✅
Important Notes
- Millisecond Timestamps: If your timestamp is in milliseconds (common in some APIs), divide by 1000 first:
timestamp = 1717209600000 / 1000 - Time Zones: This function returns UTC time. To convert to local time, you'll need to add/subtract the UTC offset for your time zone (e.g., UTC+8 would add 8 hours to the result).
- Negative Timestamps: The function currently works for timestamps >= 1970. To handle dates before the epoch (negative timestamps), you'll need to reverse the logic (subtract years/months instead of adding).
内容的提问来源于stack exchange,提问作者yum

