Thursday, October 2, 2025
HomeLanguagesGet UTC timestamp in Python

Get UTC timestamp in Python

Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps.

Note: For more information, refer to Python datetime module with examples

Example:




# Python program to demonstrate
#  datetime module
  
import datetime
  
  
dt = datetime.date(2020, 1, 26)
# prints the date as date
# object
print(dt)
  
# prints the current date
print(datetime.date.today())
  
# prints the date and time
dt = datetime.datetime(1999, 12, 12, 12, 12, 12, 342380
print(dt)
   
# prints the current date 
# and time
print(datetime.datetime.now())


Output:

2020-01-26
2020-02-04
1999-12-12 12:12:12.342380
2020-02-04 07:46:29.315237

Getting the UTC timestamp

Use the datetime.datetime.now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.

Example:




from datetime import timezone
import datetime
  
  
# Getting the current date
# and time
dt = datetime.datetime.now(timezone.utc)
  
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
  
print(utc_timestamp)


Output:

1615975803.787904
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7079 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS