askvity

How to Convert Current Time to Epoch Time in Python?

Published in Python Time Conversion 2 mins read

You can convert the current time to epoch time (also known as Unix timestamp) in Python using the time module. Epoch time represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC.

Here's how:

import time

# Get the current time in seconds since the epoch
epoch_time = time.time()

print(epoch_time)

Explanation:

  1. import time: This line imports the time module, which provides various time-related functions.
  2. time.time(): This function returns the current time as a floating-point number representing the seconds since the epoch.
  3. print(epoch_time): This line prints the epoch time to the console.

Example:

When you run the code, it will output something similar to:

1678886400.0  (This will vary based on the current time)

Alternative Method Using datetime Module:

While time.time() is the most straightforward method, you can also achieve the same result using the datetime module:

import datetime
import time

# Get the current time
now = datetime.datetime.now()

# Convert the datetime object to epoch time
epoch_time = time.mktime(now.timetuple())

print(epoch_time)

Explanation:

  1. import datetime: Imports the datetime module.
  2. now = datetime.datetime.now(): Gets the current date and time as a datetime object.
  3. now.timetuple(): Converts the datetime object to a time tuple.
  4. time.mktime(): Converts the time tuple to epoch time (a floating-point number).

Integer Conversion:

If you need the epoch time as an integer, you can simply convert the result of time.time() to an integer:

import time

epoch_time_int = int(time.time())

print(epoch_time_int)

This will truncate the decimal part of the floating-point number, giving you the number of whole seconds since the epoch.

Related Articles