Of course. Working with timestamps in Python 2.7 is a common task, especially when maintaining older systems. Here's a comprehensive guide covering the main concepts, libraries, and practical examples.

Key Concepts in Python 2.7
timemodule: This is the standard, built-in library for time-related functions. It primarily deals with timestamps as floating-point numbers (seconds since the epoch) and a special tuple format.datetimemodule: This is the more modern and object-oriented way to handle dates and times. It's highly recommended for most tasks because it's less error-prone than manual calculations with thetimemodule.- Epoch: The "start of time" for timestamps. On most systems (including Unix, Linux, macOS), this is January 1, 1970, 00:00:00 UTC.
Using the time Module
The time module is great for getting the current time and simple conversions.
a) Get Current Timestamp
Use time.time() to get the current time in seconds since the epoch as a float.
import time # Get the current timestamp current_timestamp = time.time() print "Current timestamp:", current_timestamp # Example output: Current timestamp: 1678886400.123456
b) Convert Timestamp to a Readable String (time.ctime)
The simplest way to format a timestamp is time.ctime().
import time timestamp = 1678886400.123456 readable_time = time.ctime(timestamp) print "Timestamp:", timestamp print "Readable time:", readable_time # Example output: # Timestamp: 1678886400.12 # Readable time: Wed Mar 15 12:00:00 2025
c) Convert Timestamp to a Structured Tuple (time.localtime)
For more control, you can convert a timestamp to a struct_time object. This is a 9-element tuple.

import time timestamp = 1678886400.123456 # time.localtime converts to the local timezone time_tuple = time.localtime(timestamp) print "Time tuple:", time_tuple # Example output: # Time tuple: time.struct_time(tm_year=2025, tm_mon=3, tm_mday=15, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=74, tm_isdst=0) # You can access individual elements print "Year:", time_tuple.tm_year print "Month:", time_tuple.tm_mon print "Day:", time_tuple.tm_mday # Example output: # Year: 2025 # Month: 3 # Day: 15
Using the datetime Module (Recommended)
The datetime module is more powerful and easier to work with for complex date manipulations.
a) Get Current Time as a datetime Object
from datetime import datetime # Get current time in UTC now_utc = datetime.utcnow() print "Current UTC time:", now_utc # Example output: Current UTC time: 2025-03-15 12:00:00.123456 # Get current time in local timezone now_local = datetime.now() print "Current local time:", now_local # Example output: Current local time: 2025-03-15 08:00:00.123456 (if in EST)
b) Convert datetime Object to a Timestamp
This is a very common operation. The timestamp() method does this for you.
from datetime import datetime # Create a specific datetime object dt_object = datetime(2025, 3, 15, 12, 0, 0) # Convert the datetime object to a timestamp timestamp = dt_object.timestamp() print "Datetime object:", dt_object print "Timestamp:", timestamp # Example output: # Datetime object: 2025-03-15 12:00:00 # Timestamp: 1678886400.0
c) Convert Timestamp to a datetime Object
This is the reverse operation and is crucial for parsing data from APIs or databases.
import time from datetime import datetime timestamp = 1678886400.0 # Method 1: Using datetime.utcfromtimestamp (for UTC) dt_object_utc = datetime.utcfromtimestamp(timestamp) # Method 2: Using datetime.fromtimestamp (for local timezone) dt_object_local = datetime.fromtimestamp(timestamp) print "Timestamp:", timestamp print "Datetime (UTC):", dt_object_utc print "Datetime (Local):", dt_object_local # Example output: # Timestamp: 1678886400.0 # Datetime (UTC): 2025-03-15 12:00:00 # Datetime (Local): 2025-03-15 08:00:00 (if in EST)
d) Formatting a datetime Object into a String
Use the strftime() method to format a datetime object into any string representation you need.

from datetime import datetime
dt_object = datetime(2025, 3, 15, 12, 0, 0)
# Common format: YYYY-MM-DD HH:MM:SS
formatted_str_1 = dt_object.strftime("%Y-%m-%d %H:%M:%S")
print "Formatted (1):", formatted_str_1
# Example output: Formatted (1): 2025-03-15 12:00:00
# Another common format: MM/DD/YYYY
formatted_str_2 = dt_object.strftime("%m/%d/%Y")
print "Formatted (2):", formatted_str_2
# Example output: Formatted (2): 03/15/2025
# Including AM/PM
formatted_str_3 = dt_object.strftime("%I:%M:%S %p")
print "Formatted (3):", formatted_str_3
# Example output: Formatted (3): 12:00:00 PM
e) Parsing a String into a datetime Object
Use the strptime() function to parse a string into a datetime object. You must provide the exact format string that matches the input.
from datetime import datetime date_string = "2025-03-15 12:00:00" format_string = "%Y-%m-%d %H:%M:%S" # Parse the string into a datetime object dt_object = datetime.strptime(date_string, format_string) print "Parsed datetime:", dt_object # Example output: Parsed datetime: 2025-03-15 12:00:00
Using the calendar Module
The calendar module is useful for getting information about dates, like the day of the week.
import time import calendar timestamp = 1678886400.0 time_tuple = time.localtime(timestamp) # Get the weekday (Monday is 0, Sunday is 6) weekday_num = time_tuple.tm_wday weekday_name = calendar.day_name[weekday_num] print "Timestamp:", timestamp print "Weekday Name:", weekday_name # Example output: # Timestamp: 1678886400.0 # Weekday Name: Wednesday
Summary Table: Key Functions
| Task | time Module |
datetime Module |
|---|---|---|
| Get Current Timestamp | time.time() |
datetime.now().timestamp() |
| Get Current Time as Object | time.localtime() (returns a struct_time) |
datetime.now() (returns a datetime object) |
| Convert Timestamp to String | time.ctime(ts) or time.strftime(fmt, ts_tuple) |
datetime.fromtimestamp(ts).strftime(fmt) |
| Convert String to Timestamp | Manual parsing with time.strptime is complex |
datetime.strptime(s, fmt).timestamp() |
| Convert Timestamp to Object | time.localtime(ts) (returns a struct_time) |
datetime.fromtimestamp(ts) (returns a datetime) |
| Convert Object to Timestamp | time.mktime(ts_tuple) |
dt_object.timestamp() |
| Timezone Handling | Very limited | Better, but still requires the pytz library for full IANA support |
Important Considerations for Python 2.7
- No
timestamp()method ondatetimeobjects: This is a major difference from Python 3. In Python 2.7, you cannot call.timestamp()on adatetimeobject. You must calculate it manually if you need it.# Python 2.7 workaround to get timestamp from datetime from datetime import datetime, timedelta epoch = datetime(1970, 1, 1) dt_object = datetime(2025, 3, 15, 12, 0, 0) timestamp = (dt_object - epoch).total_seconds() print "Manual timestamp:", timestamp # Output: 1678886400.0
