How to convert a date to a UTC timestamp?

To convert a date to a UTC timestamp we can use different solutions such as a programming language like Python or Unix command-line tool "date". A resulting timestamp is the number of milliseconds since the Unix epoch. Look for code snippets below.


Python:

import datetime

# create a datetime object with the desired date and time in local time
dt = datetime.datetime(2023, 2, 28, 12, 0, 0)

# convert the datetime object to UTC by replacing the timezone information
utc_dt = dt.replace(tzinfo=datetime.timezone.utc)

# convert the UTC datetime object to a Unix timestamp
timestamp = int(utc_dt.timestamp() * 1000)

Unix command:

date -u -d "2023-02-28 12:00:00" +%s%3N


Have a question?