askvity

How to get Unix time in Python?

Published in Python Programming 2 mins read

You can obtain the Unix time (also known as epoch time) in Python by using the datetime module and its timestamp() method.

Here's how:

  1. Import the datetime module: This module provides classes for manipulating dates and times.

  2. Get the current datetime: Use datetime.datetime.now() to get the current date and time.

  3. Convert to Unix time: Call the .timestamp() method on the datetime object to get the Unix timestamp as a floating-point number representing the number of seconds since the epoch (January 1, 1970, 00:00:00 UTC).

Here's the code example:

import datetime

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

# Convert to Unix timestamp
unix_timestamp = now.timestamp()

print(unix_timestamp)

This code will print the current Unix timestamp. You can also use datetime.datetime.utcnow() if you specifically want the UTC time.

import datetime

# Get the current UTC datetime
now_utc = datetime.datetime.utcnow()

# Convert to Unix timestamp
unix_timestamp_utc = now_utc.timestamp()

print(unix_timestamp_utc)

Explanation:

  • The datetime.datetime.now() and datetime.datetime.utcnow() functions return datetime objects representing the current local time and the current UTC time, respectively.
  • The .timestamp() method converts a datetime object to a floating-point number representing seconds since the epoch. The return value is the number of seconds that have elapsed between the Unix epoch and the datetime provided.

Related Articles