askvity

How do you convert time in Python?

Published in Python Time Conversion 4 mins read

You can convert time in Python using several built-in modules and functions, most notably the time and datetime modules. The specific method depends on the format you're starting with and the format you want to achieve.

Here's a breakdown of common conversions and how to accomplish them:

Converting Epoch Time (Seconds Since the Epoch)

Epoch time (also known as Unix time or POSIX time) represents the number of seconds that have elapsed since January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC).

  • To local time (human-readable format):

    You can use time.ctime():

    import time
    
    epoch_time = time.time()  # Get current epoch time
    local_time = time.ctime(epoch_time)
    print(local_time)  # Output: e.g., 'Tue Oct 24 12:34:56 2023'

    This function takes the epoch time as an argument and returns a string representing the local time.

  • To a struct_time object:

    Use time.localtime() or time.gmtime():

    import time
    
    epoch_time = time.time()
    local_time_struct = time.localtime(epoch_time) # Local time
    utc_time_struct = time.gmtime(epoch_time) # UTC time
    
    print(local_time_struct)
    # Output (example): time.struct_time(tm_year=2023, tm_mon=10, tm_mday=24, tm_hour=12, tm_min=34, tm_sec=56, tm_wday=1, tm_yday=297, tm_isdst=0)
    
    print(utc_time_struct)
    # Output (example): time.struct_time(tm_year=2023, tm_mon=10, tm_mday=24, tm_hour=16, tm_min=34, tm_sec=56, tm_wday=1, tm_yday=297, tm_isdst=0)

    time.localtime() returns a struct_time object representing local time, while time.gmtime() returns a struct_time object representing UTC time (Greenwich Mean Time). A struct_time object is a tuple-like object with named fields representing different components of the time (year, month, day, hour, minute, second, etc.).

Converting Between Time Zones

You can use libraries like pytz or zoneinfo (part of the standard library since Python 3.9) for timezone conversions.

import datetime
import pytz  # Or use zoneinfo with Python 3.9+
# Example with pytz
utc = pytz.utc
eastern = pytz.timezone('US/Eastern')

now = datetime.datetime.utcnow()
utc_now = utc.localize(now)
eastern_now = utc_now.astimezone(eastern)

print(f"UTC Time: {utc_now}")
print(f"Eastern Time: {eastern_now}")

Converting Strings to Time Objects

Use the datetime module's strptime() method to parse strings into datetime objects.

from datetime import datetime

time_string = "2023-10-24 13:45:00"
time_format = "%Y-%m-%d %H:%M:%S"  # Define the format of the string

datetime_object = datetime.strptime(time_string, time_format)
print(datetime_object) # Output: 2023-10-24 13:45:00

The strptime() function takes the time string and a format string as arguments. The format string specifies how the time string is formatted (e.g., %Y for year, %m for month, %d for day, %H for hour, %M for minute, %S for second). Consult the Python documentation for a complete list of format directives.

Converting Time Objects to Strings

Use the strftime() method of datetime objects to format them as strings.

from datetime import datetime

now = datetime.now()
formatted_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print(formatted_time) # Example Output: 10/24/2023, 17:00:00

The strftime() function takes a format string as an argument and returns a string representing the datetime object in the specified format.

Converting to Different Date/Time Formats

Once you have a datetime object, you can easily convert it to different formats using strftime():

from datetime import datetime

now = datetime.now()

# ISO 8601 format
iso_format = now.isoformat()
print(iso_format)  # Output: e.g., '2023-10-24T17:00:00.123456'

# Custom format
custom_format = now.strftime("%A, %B %d, %Y")
print(custom_format)  # Output: e.g., 'Tuesday, October 24, 2023'

In summary, Python offers comprehensive tools for handling various time conversions. The correct approach depends on the initial time format and the desired output format. Understanding the time and datetime modules is key to effective time manipulation in Python.

Related Articles