Python parse unix time

Python 3: Unix Timestamp

A Unix timestamp is the number of seconds that have passed (elapsed) since the epoch (January 1, 1970 at 00:00:00 UTC). It provides a way to express any date and time as a single number without having to worry about multiple unit components (like hours and minutes) and time zones (since it uses UTC).

Python 3 provides functions for working with timestamps based on the operating system’s definition of «epoch,» which may be different from Unix’s definition. However, Windows and Unix-like systems such as Linux and macOS (10 and above) all use Unix’s definition of epoch (i.e., 1970-01-01 00:00:00 UTC), so Python’s timestamp functions are effectively Unix timestamp functions when they’re called on these operating systems. This article assumes we’re using one of these operating systems.

Current Unix Timestamp

Second Precision

In Python 3, we can get the Unix timestamp for the current time by using the built-in time module:

import time now = int( time.time() ) print( now )

The time.time() function by itself returns the Unix timestamp as a float , with any value to the right of the decimal point representing fractions of a second. However, Python does not make any guarantees about the exact level of precision of this number beyond whole seconds (the exact precision varies depending on the operating system). So in the example above, we convert it into an integer using the built-in int() function, which truncates float s toward zero (i.e., simply removes the fractional value for both positive and negative numbers).

Читайте также:  Css фон градиент примеры

Nanosecond Precision (Python 3.7 and Up)

On Python 3.7 and higher, we can get a guaranteed higher precision timestamp using the time.time_ns() function, which returns an integer representing the number of nanoseconds since the epoch. To get the current nanosecond precision timestamp, we can write:

import time now_ns = time.time_ns() print( now_ns )

Millisecond Precision (Python 3.7 and Up)

If we want millisecond precision, we can simply divide the nanosecond timestamp provided by time.time_ns() by 1,000 and then truncate:

import time now_ms = int( time.time_ns() / 1000 ) print( now_ms )

Convert datetime to Unix Timestamp

To convert a date and time specified in our operating system’s local time zone, we can first create a datetime object representing the date and time and then convert it to a Unix timestamp using the .timestamp() method.

For example, to get the Unix timestamp (in UTC) for 2021-03-05 14:30:21 in the system’s local time zone, we can write:

from datetime import datetime dt = datetime( 2021, 3, 5, 14, 30, 21 ) timestamp = int( dt.timestamp() ) print( timestamp )

On Python versions 3.2 and higher, we can use the timezone class to specify any time zone we want. For example, to convert a datetime specified in UTC, we can write:

# Python 3.2 or higher required from datetime import datetime, timezone dt = datetime( 2021, 3, 5, 14, 30, 21, tzinfo=timezone.utc ) timestamp = int( dt.timestamp() ) print( timestamp )

Convert Unix Timestamp to datetime

If we want to find out what date and time a specific Unix timestamp represents, we can convert the timestamp to a datetime object.

For example, to convert a Unix timestamp to a datetime in the system’s local time zone, we can write:

from datetime import datetime timestamp = 1614983421 dt = datetime.fromtimestamp( timestamp ) print( dt )

On Python versions 3.2 and higher, we can use the timezone class to convert Unix timestamps into other time zones. For example, to get the UTC datetime corresponding to the Unix timestamp 1614954621 , we can write:

# Python 3.2 or higher required from datetime import datetime, timezone timestamp = 1614954621 dt = datetime.fromtimestamp( timestamp, tz=timezone.utc ) print( dt )

References

Источник

Easily Convert Unix time to Datetime in Python

python convert unix time to datetime

In this article, we will be discussing Unix time and how to convert Unix time to datetime in Python. Before we review the Python implementations, let’s discuss what the concept of Unix time is.

Читайте также:  Php str replace замена одной

In the field of computing, Unix time is a digital timestamp. Unix time represents the number of seconds passed since the Unix epoch without including leap seconds.

What is the Unix epoch? This epoch is nothing but a date and time set by Unix engineers to establish the start of Unix time. The date is New Year’s Day, 1970, at exactly 00:00:00 UTC. Therefore, the total number of seconds since January 1st, 1970, 00:00:00 UTC, is the current Unix time.

What is the Unix Time Format?

A single signed number represents Unix time which increases each second.

As of writing this article, the UNIX time is: 1661324766

This means 1,661,324,766 seconds have passed since Unix Epoch.

What is Datetime Module, and What are Datetime Objects?

Python datetime module is a part of the Python standard library under the “datatypes” category. The DateModule provides multiple classes to handle dates and times in different formats.

A Datetime object is an instance created within the Python class. datetime . datetime . In the datetime module, there are 2 types of objects

  • Naive Objects – Doesn’t contain timezone information
  • Aware Objects – A localized datetime object based on a timezone.

How to Convert Unix Time to a Python Datetime Object?

As we’ve discussed, we use the Datetime module to handle dates and times. With the help of the fromtimestamp() function, we can convert Unix time to a datetime object in Python. Within the function, pass Unix time as an argument.

Let’s look at the following implementation:

import datetime unixToDatetime = datetime.datetime.fromtimestamp(1661324766) # Unix Time print(unixToDatetime)
Output

How to Convert Datetime Object to Unix time in Python

Using the timestamp() function from the Datetime module, we can convert the Datetime object to Unix time. The function will return a float value representing the Unix time.

Let’s use the datetime object ( unixToDatetime ) created in the previous demonstration

datetimeToUnix = unixToDatetime.timestamp() print(datetimeToUnix)

How To Convert Unix Time To Datetime in Pandas Dataframes

Let’s say a data frame consists of a column containing Unix time values. How do we convert the values of this column into standard date and time?

Читайте также:  Парсинг email адресов python

Using the to_datetime() function from the Datetime module, we can solve our problem.

Here’s our sample data frame(df):

date price 0 1349720105 2300.23 1 1349806505 8776.11 2 1349892905 9009.33 3 1350065705 2223.22

Let’s see how the function is implemented in this scenario:

import pandas as pd from datetime import datetime df df['date'] = pd.to_datetime(df['date'],unit='s') # Changing the values of the column
Output
date price 0 2012-10-08 18:15:05 2300.23 1 2012-10-09 18:15:05 8776.11 2 2012-10-10 18:15:05 9009.33 3 2012-10-12 18:15:05 2223.22

Observe that all values in the “Date” column are now Datetime objects.

How To Convert a Unix timestamp in Nanoseconds to Date and Time

By converting the Unix time to a datetime object, we can present it in a human-readable format. Let’s look at the following implementation

from datetime import datetime # flooring the value by 1 billion readableDt = datetime.fromtimestamp( 1220287113082844499 // 1000000000) readableDt
Output
datetime.datetime(2008, 9, 1, 16, 38, 33)

Tip: To format the result in YYYY/MM/DD H: M: S, use the . strftime() method

How To Convert Datetime Object To a Specific Timezone

Time Zone conversion is an essential feature that this module provides. Using the .astimezone function, we can achieve such requirements.

The following program converts from UTC to America/Los Angeles.

from datetime import datetime, timezone, ZoneInfo dt_UTC = datetime.now(timezone.utc) dt_LA = dt_UTC.astimezone(tz=datetime.ZoneInfo("America/Los_Angeles")) print(dt_LA)
Output

FAQs on Python Convert UNIX time to datetime

You can display Unix time as normal time by converting it to a Datetime object. Use the fromtimestamp() function.

Unix time is represented as a single signed value that denotes the number of seconds since the Unix Epoch.

First, convert the Unix timestamp to a Datetime object using fromtimestamp() . Then, convert the default timezone of the Datetime object to UTC using astimezone() .

Conclusion

In this article, we have discussed the concept of UNIX time and its origin. Unix time is the number of seconds since the Unix Epoch. The Unix Epoch is a date set by UNIX engineers to represent the start of Unix time. Unix time is represented within a single signed value.

We have discussed techniques to convert Unix times to Datetime objects and vice-versa. We have also discussed techniques to convert Unix time values in Pandas data frames.

Источник

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