Python time to unixtime

Convert between Unix time (Epoch time) and datetime in Python

This article explains how to convert between Unix time (also called Epoch time or Posix time) and the datetime object, which represents dates and times in Python.

See the following article for basic information on the datetime module, which handles date and time.

Unix time is also used to represent file timestamps, such as creation and modification dates. The current UNIX time can be obtained with time.time() . For more information, see the following articles.

What is Unix time (Epoch time, Posix time)?

Unix time is the number of seconds that have elapsed since the Unix epoch, 00:00:00 UTC (Coordinated Universal Time) on January 1, 1970. It is also known as Epoch time, Posix time, and so on.

Unix time (also known as Epoch time, Posix time, seconds since the Epoch, or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970 (an arbitrary date). Unix time — Wikipedia

Convert Unix time (Epoch time) to datetime : fromtimestamp()

To work with dates and times in Python, use the datetime module.

Use datetime.fromtimestamp() from the datetime module to convert Unix time (Epoch time) to a datetime object. Pass Unix time as an argument.

By default, the conversion outputs local date and time. For example, if your machine is set to Japan Standard Time (JST), the time difference (+9 hours) is taken into account.

When 0 is passed as an argument:

import datetime dt = datetime.datetime.fromtimestamp(0) print(dt) # 1970-01-01 09:00:00 print(type(dt)) # print(dt.tzinfo) # None 

By default, the function returns naive datetime objects with their tzinfo attribute set to None .

You can also provide a second argument, tz , to specify a time zone. The tzinfo attribute will be set, and an aware datetime object with the date and time correctly converted to the specified time zone will be returned.

dt_utc_aware = datetime.datetime.fromtimestamp(0, datetime.timezone.utc) print(dt_utc_aware) # 1970-01-01 00:00:00+00:00 print(dt_utc_aware.tzinfo) # UTC dt_jst_aware = datetime.datetime.fromtimestamp(0, datetime.timezone(datetime.timedelta(hours=9))) print(dt_jst_aware) # 1970-01-01 09:00:00+09:00 print(dt_jst_aware.tzinfo) # UTC+09:00 

datetime.utcfromtimestamp() , which returns a naive datetime object in UTC (= tzinfo is None ), is also available.

dt_utc_naive = datetime.datetime.utcfromtimestamp(0) print(dt_utc_naive) # 1970-01-01 00:00:00 print(dt_utc_naive.tzinfo) # None 

Convert datetime to Unix time (Epoch time): timestamp()

Use the timestamp() method to convert a datetime object to Unix time (Epoch time). Unix time is returned as a floating point number float .

Use the datetime object created by the sample code above as an example.

print(dt) # 1970-01-01 09:00:00 print(dt.timestamp()) # 0.0 print(type(dt.timestamp())) # 

Naive objects having their tzinfo attribute set to None are converted based on the environment’s timezone, while aware objects with a defined tzinfo attribute are converted using their timezone.

Note that the object created by utcfromtimestamp() is naive in UTC (= tzinfo is None ), so the result is different from the other objects.

print(dt_utc_aware) # 1970-01-01 00:00:00+00:00 print(dt_utc_aware.timestamp()) # 0.0 print(dt_jst_aware) # 1970-01-01 09:00:00+09:00 print(dt_jst_aware.timestamp()) # 0.0 print(dt_utc_naive) # 1970-01-01 00:00:00 print(dt_utc_naive.timestamp()) # -32400.0 

If time zones are not a concern, you can disregard them since both fromtimestamp() and timestamp() methods convert times based on the machine’s local time by default.

Источник

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

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

Источник

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.

Источник

Читайте также:  Рамка вокруг таблицы
Оцените статью