Python parse datetime to timestamp

Convert DateTime to Unix timestamp in Python

This tutorial will look at how to convert DateTime to Unix timestamp in Python and String Date to timestamp with examples.

What is Unix Timestamp?

Unix was initially developed between 1960 – and 1970. The start time of the Unix was set to January 1, 1970, GMT (Midnight Greenwich Mean Time). The ISO format is represented as ISO 8601: 1970-01-01T00:00:00Z

In Computing, “Epoch Time” refers to the starting point used to calculate the number of seconds elapsed.

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT) and not counting the leap seconds.

How to convert DateTime to Unix Timestamp in Python?

It is common to store the DateTime as a Timestamp in the Database, and most Databases have a timestamp data type. It has a lot of benefits as it’s easier to track the created and modified records in the Database. It also occupies lesser space in DB when compared to DateTime datatype.

Now that we know the history of the Unix timestamp and how it is calculated, let us look at how to convert the DateTime object to Unix Timestamp in Python.

Example 1 – How to get the Current timestamp in Python using datetime module?

Using the Python’s datetime module we first get the current date and time using datetime.now() method, and we can pass the current datetime to datetime.timestamp() method to obtain the Unix timestamp.

from datetime import datetime # current date and time currentDateTime = datetime.now() print("Current Date Time is ", currentDateTime) # convert datetime to timestamp timestamp = datetime.timestamp(currentDateTime) print("Current Unix Timestamp is ", timestamp) 
Current Date Time is 2022-04-23 21:39:43.821740 Current Unix Timestamp is 1650730183.82174

Example 2 – How to convert string date to timestamp in Python

We leverage the strptime() method to convert the string to a datetime object. We cannot create the datetime object from any string, meaning a string needs to be in a specific format to convert it into a datetime object.

We first convert it into a given string into a date object using the strptime() and then convert it into the time tuple.

Using the time module’s mktime() method, we can pass the time tuple to convert it into the Unix timestamp.

import time import datetime # date in string format dt="23/04/2022" # convert into the time tuple time_tuple=datetime.datetime.strptime(dt, "%d/%m/%Y").timetuple() print("Time tuple format ",time_tuple) # using mktime() convert to timestamp print("The timestamp is ",time.mktime(time_tuple))
Time tuple format time.struct_time(tm_year=2022, tm_mon=4, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=113, tm_isdst=-1) The timestamp is 1650652200.0

Conclusion

There are multiple ways to convert Datetime to Unix timestamp in Python. The two best approaches are using the mktime() method in the time module if the date is passed as a string object. If we have to get the current timestamp, we can leverage the datetime.timestamp() method.

Читайте также:  Javascript убрать повторяющиеся элементы массива

Источник

Timestamp In Python

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.

timestamp representation

Get Current Timestamp

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

Datetime to Timestamp

The timestamp() 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 datetime.now() method.
  • Next, pass the current datetime to the datetime.timestamp() method to get the UNIX timestamp
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)
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 int(ts) constructor.

Читайте также:  Selenium java wait element clickable

Get Timestamp Using time Module

The time module‘s time() method returns the current time in the timestamp format, which is nothing but the time elapsed from the epoch time, January 1, 1970.

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 calendar Module

Use the calendar module’s calendar.timegm() 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 time.gmtime() method.
  • At last, pass it to the Use the calendar.timegm() method to get a timestamp
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.

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 datetime object using the fromtimestamp() method that is available in the datetime module.

datetime.fromtimestamp(timestamp, tz=None)

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

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

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 time.time() .

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

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)
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.

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 timestamp() method.

Читайте также:  Php узнать вес файла

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 tzinfo parameter of the datetime object and then call the timestamp() method.

Example: Get timestamp from datetime with UTC timezone

from datetime import datetime from datetime import timezone birthday = "23.02.2021 09:12:00" # convert to datetime date_time = datetime.strptime(birthday, '%d.%m.%Y %H:%M:%S') # get UTC timestamp utc_timestamp = date_time.replace(tzinfo=timezone.utc).timestamp() print(utc_timestamp) # Output 1614071520.0

Timestamp from datetime with a Different Timezone

We have seen how to get the timestamp information from a datetime object with a timezone set as UTC.

Similarly , we can get timestamp information from a datetime object with a timezone different than the UTC. This could be done with strptime() with the offset information.

from datetime import datetime # Timezone Name. date_String = "23/Feb/2012:09:15:26 UTC +0900" dt_format = datetime.strptime(date_String, '%d/%b/%Y:%H:%M:%S %Z %z') print("Date with Timezone Name::", dt_format) # Timestamp timestamp = dt_format.timestamp() print("timestamp is::", timestamp)
Date with Timezone Name:: 2012-02-23 09:15:26+09:00 timestamp is:: 1329956126.0

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 datetime object using the same fromtimestamp() or utcfromtimestamp () method.

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

import datetime timestamp_int = 1329988320000 date = datetime.datetime.utcfromtimestamp(timestamp_int / 1e3) print("Corresponding date for the integer timestamp is::", date)
Corresponding date for the integer timestamp is:: 2012-02-23 09:12:00

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью