Cara menggunakan python datetime to timestamp

Python provides various libraries to work with timestamp data. For example, the datetime and time module helps in handling the multiple dates and time formats. In addition to this, it supports various functionalities involving the timestamp and timezone.

After reading this tutorial, you’ll learn: –

  • How to get the curent timestamp in Python
  • Convert timestamp to a datetime
  • Convert datetime to timestamp
  • Format timestamp to string object and vice-versa
  • How to get the timestamp object with an offset into a date-time object.

Table of contents

What is Timestamp in Python

A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred. This information could be accurate to the microseconds. It is a POSIX timestamp corresponding to the datetime instance.

In general, the date and time data are saved in the UNIX timestamp format. A UNIX time or Epoch or POSIX time is the number of seconds since the Epoch.

Unix time (also known as Epoch time, POSIX time, seconds since the Epoch, or UNIX Epoch time) describes a point in time.

It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds.

The Unix epoch is 00:00:00 UTC on 1 January 1970 (an arbitrary date); leap seconds are ignored, with a leap second having the same Unix time as the second before it, and every day is treated as if it contains exactly 86400 seconds.

Wikipedia.

The reason we are using the UNIX epoch time as 1 January 1970 is because of the fact that UNIX came into business around that time frame.

The below image shows how a particular date and time is represented in different formats.

Cara menggunakan python datetime to timestamp
Cara menggunakan python datetime to timestamp
timestamp representation

Get Current Timestamp

To get the current timestamp in Python, use any of the following three modules.

  • datetime
  • time
  • calendar

Datetime to Timestamp

The

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
5 method of a datetime module returns the POSIX timestamp corresponding to the datetime instance. The return value is float.

  • First, Get the current date and time in Python using the
    Date and time is: 2021-07-03 16:21:12.357246
    Timestamp is: 1625309472.357246
    6 method.
  • Next, pass the current datetime to the
    Date and time is: 2021-07-03 16:21:12.357246
    Timestamp is: 1625309472.357246
    7 method to get the UNIX timestamp

Example

from datetime import datetime

# Getting the current date and time
dt = datetime.now()

# getting the timestamp
ts = datetime.timestamp(dt)

print("Date and time is:", dt)
print("Timestamp is:", ts)

Output:

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246

Note: Note: It returns timestamp in float type to get timestamp without decimal value convert it to an integer using the

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
8 constructor.

Get Timestamp Using Date and time is: 2021-07-03 16:21:12.357246 Timestamp is: 1625309472.3572469 Module

The time module‘s

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
0 method returns the current time in the timestamp format, which is nothing but the time elapsed from the epoch time, January 1, 1970.

  • First, import the time module
  • Next, use the time.time() method to get the timestamp

Definition: This function returns the time in seconds since the epoch as a floating-point number.

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347

Get Timestamp Using import time # current timestamp x = time.time() print("Timestamp:", x) # Output 1625309785.4823471 Module

Use the calendar module’s

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
2 method to convert the current time to the timestamp.

  • First, import both time and the calendar modules.
  • Next, get the GMT time using the time module’s
    import time
    
    # current timestamp
    x = time.time()
    print("Timestamp:", x)
    
    # Output 1625309785.482347
    3 method.
  • At last, pass it to the Use the
    import time
    
    # current timestamp
    x = time.time()
    print("Timestamp:", x)
    
    # Output 1625309785.482347
    2 method to get a timestamp

Example:

import calendar
import time

# Current GMT time in a tuple format
current_GMT = time.gmtime()

# ts stores timestamp
ts = calendar.timegm(current_GMT)
print("Current timestamp:", ts)

# output 1625310251

Convert Timestamp to Datetime (format)

While the timestamp’s default format is just a floating-point number, there are cases when the timestamp will be represented in the ISO 8601 format. This looks something like the below value with the T and Z alphabets.

2014-09-12T19:34:29Z

Here the alphabet T stands for Time and Z stands for the Zero timezone which represents the offset from the coordinated universal time(UTC).

Let us see few examples with different date-time formats. Based on the format we will be using the format string and we can extract the timestamp information from that.

We can convert the timestamp back to

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 object using the
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
6 method that is available in the datetime module.

Syntax

datetime.fromtimestamp(timestamp, tz=None)

It returns the local date and time corresponding to the POSIX timestamp, such as is returned by 

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
7.

If optional argument 

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
8 is 
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
9 or not specified, the timestamp is converted to the platform’s local date and time, and the returned 
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 object is naive.

Example:

from datetime import datetime

# timestamp
ts = 1617295943.17321

# convert to datetime
dt = datetime.fromtimestamp(ts)
print("The date and time is:", dt)

# output 2021-04-01 22:22:23.173210

Convert Timestamp to String

We can convert the timestamp string using the datetime formatting.

  • First, convert the timestamp to a datetime instance.
  • Next, use the strftime() with formatting codes to convert timestamp to string format

It returns the local date and time corresponding to the POSIX timestamp, such as is returned by 

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
7.

If optional argument 

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
8 is 
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
9 or not specified, the timestamp is converted to the platform’s local date and time, and the returned 
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 object is naive.

Example:

from datetime import datetime

timestamp = 1625309472.357246
# convert to datetime
date_time = datetime.fromtimestamp(timestamp)

# convert timestamp to string in dd-mm-yyyy HH:MM:SS
str_date_time = date_time.strftime("%d-%m-%Y, %H:%M:%S")
print("Result 1:", str_date_time)

# convert timestamp to string in dd month_name, yyyy format
str_date = date_time.strftime("%d %B, %Y")
print("Result 2:", str_date)

# convert timestamp in HH:AM/PM MM:SS
str_time = date_time.strftime("%I%p %M:%S")
print("Result 3:", str_time)

Output:

Result 1: 03-07-2021, 16:21:12
Result 2: 03 July, 2021
Result 3: 04PM 21:12

Get Timestamp in Milliseconds

The datetime object comes with the timestamp which in turn could be displayed in milliseconds.

Example:

from datetime import datetime

# date in string format
birthday = "23.02.2012 09:12:00"

# convert to datetime instance
date_time = datetime.strptime(birthday, '%d.%m.%Y %H:%M:%S')

# timestamp in milliseconds
ts = date_time.timestamp() * 1000
print(ts)

# Output 1329968520000.0

Get The UTC timestamp

As we discussed, we can get the timestamp from the datetime object with the timezone information. We can convert a datetime object into a timestamp using the

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
5 method.

If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the

import calendar
import time

# Current GMT time in a tuple format
current_GMT = time.gmtime()

# ts stores timestamp
ts = calendar.timegm(current_GMT)
print("Current timestamp:", ts)

# output 1625310251
6 parameter of the datetime object and then call the
Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
5 method.

Example: Get timestamp from

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 with UTC timezone

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
0

Timestamp from import time # current timestamp x = time.time() print("Timestamp:", x) # Output 1625309785.4823475 with a Different Timezone

We have seen how to get the

2014-09-12T19:34:29Z
0 information from a
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 object with a timezone set as
2014-09-12T19:34:29Z
2

Similarly

2014-09-12T19:34:29Z
3 we can get
2014-09-12T19:34:29Z
0 information from a datetime object with a timezone different than the UTC. This could be done with
2014-09-12T19:34:29Z
5 with the offset information.

Read: Working with timezone in Python.

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
1

Output

Date and time is: 2021-07-03 16:21:12.357246
Timestamp is: 1625309472.357246
2

Convert an Integer Timestamp to Datetime

We have seen how we can display the timestamp in milliseconds. Similarly, we can convert a timestamp value in integer to

import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
5 object using the same
import time

# current timestamp
x = time.time()
print("Timestamp:", x)

# Output 1625309785.482347
6 or
2014-09-12T19:34:29Z
8() method.

In the below example we are considering the timestamp in milliseconds and finding its corresponding datetime object. We are using the constant

2014-09-12T19:34:29Z
9 for normalizing the value.