Fromtimestamp utc python 3

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

Читайте также:  Увеличить размер массива php

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

Источник

5 Examples to Understand Python FromTimeStamp Better

Python FromTimeStamp

Hello Geeks! Welcome back to another article, i.e., Python fromtimestamp(). So, this one comes from the python DateTime module. So today, in this article, first, we will take a quick overview of the python timestamp and then will see the fromtimestamp() method from the Date class. Let’s get started.

Python Timestamp

Now, once we have overviewed about Datetime Module, take a look at Python Timestamp. So, first, understand what timestamp is? So, a timestamp is encoded information for the time of any particular happening. Talking more convincingly, we can say that the timestamp refers to a group of encoded characters representing any particular date-time, including seconds. However, we don’t need to worry about encoding as python handles it. Now, the question is how to get a timestamp. A simple answer for this is that different modules have their methods to create a timestamp. For example:-

Module Methods
Time Module time.time()
DateTime Module datetime_obj.timestamp()
Calender calender_obj.timegm()

Example

#importing datetime class from datetime module. from datetime import datetime random_date = datetime(2010,11,12,13,14,15) print(random_date) ts = random_date.timestamp() # Converting date into timestamp print(ts)
2010-11-12 13:14:15 1289567655.0

Now, once we understand timestamp, let’s see the python fromtimestamp() method.

Python Fromtimestamp()

So, this function is from the DateTime class and Date class of the DateTime module. We can Access it as datetime.datetime.fromtimestamp() or datetime.date.fromtimestamp() respectively. What this function does is return the date corresponding to any particular timestamp. We need to pass the timestamp object as the argument of this function, and in return, it gives us the datetime object corresponding to the given timestamp.

Example 1:- Converting timestamp to Datetime Object

#importing datetime class from datetime module from datetime import datetime #Creating a timestamp datetime_obj = datetime(2010,11,12,13,14,15) print(datetime_obj) ts = datetime_obj.timestamp() # Converting date into timestamp print(ts) # Converting timestamp to date datetime_obj2 = datetime.fromtimestamp(ts) print("Converted time stamp from datetime class",datetime_obj2)
2010-11-12 13:14:15 1289567655.0 Converted time stamp from datetime class 2010-11-12 13:14:15

Example 2:- Converting timestamp to Date Object

#importing date class from datetime module from datetime import date #Creating a timestamp datetime_obj = datetime(2010,11,12,13,14,15) print(datetime_obj) ts = datetime_obj.timestamp() # Converting date into timestamp print(ts) # Converting timestamp to date date_obj = date.fromtimestamp(ts) print("Converted time stamp from date class",date_obj)
2010-11-12 13:14:15 1289567655.0 Converted time stamp from date class 2010-11-12

Example 3:- Python fromtimestamp for UTC

UTC stands for Universal Time Coordinated. It is the standard used by the international community to keep time. Let’s see how we can create a timestamp for that and then get a datetime object from that timestamp.

from datetime import datetime,timezone # Getting the current date # and time dt = datetime.now(timezone.utc) print("dt object datatype",type(dt)) print(dt) # Converting datetime object utc_timestamp = dt.timestamp() print("Datatype of utc_timestamp",type(utc_timestamp)) print(utc_timestamp) print(type(utc_timestamp)) #Converting timestamp to datetime object datetime_obj2 = datetime.fromtimestamp(utc_timestamp) print("Converted timestamp from datetime class",datetime_obj2)
dt object datatype 2021-11-27 17:32:34.626788+00:00 Datatype of utc_timestamp 1638034354.626788 Converted timestamp from datetime class 2021-11-27 17:32:34.626788

Example 4:- Python fromtimestamp Set Timezone

#importing datetime class from datetime module from datetime import datetime import pytz #Creating a timestamp ACST = pytz.timezone('Australia/Darwin') datetime_obj = datetime(1901,11,12,13,14,15, tzinfo=ACST) print(datetime_obj) ts = datetime_obj.timestamp() # Converting date into timestamp print(ts) print(type(ts)) # Converting timestamp to date datetime_obj2 = datetime.fromtimestamp(ts,tz=ACST) print("Converted time stamp from datetime class",datetime_obj2)
1901-11-12 13:14:15+08:43 -2150220525.0 Converted time stamp from datetime class 1901-11-12 13:14:15+08:43

Example 5:- Python datetime fromtimestamp milliseconds

from datetime import datetime time_in_millis = 1596542285000 datetime_obj = datetime.fromtimestamp(time_in_millis/1000) print(datetime_obj)

Errors while using fromtimestamp()

Error: Python datetime fromtimestamp yielding valueerror year out of range

f = 1437506779950.0 print(datetime.fromtimestamp(float(f))) Output: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 1 f = 1437506779950.0 2 ----> 3 print(datetime.fromtimestamp(float(f))) ValueError: year 47522 is out of range 

The error is that we need to divide f to 1000 to convert milliseconds to seconds for computation.

f = 1437506779950.0 print(datetime.fromtimestamp(float(f)/1000))

Error: Python fromtimestamp() method inconsistent

This error is occurred due to an inconsistent timezone defined while using the function. Here is the complete list of timezones.

Conclusion

So, today in this article, we took the overview of the Python Datetime module. Then we discussed different classes in that module. After that, we have seen what timestamps are and how we can create a timestamp. In the end, we have seen how we can convert a timestamp to a datetime and date object using the fromtimestamp() method from both classes.

I hope this article has helped you. Keep supporting. Thank You.

Источник

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