Python unix time to string

Unix Timestamp to datetime in Python

In this post, we are going to learn how to convert Unix Timestamp to datetime in Python with examples. First, we will get the current epoch in Python and then use this in our examples to use it convert the UNIX timestamp to datetime

What is Python Epoch time?

The Unix time is also known as epoch time. It represents the time passed since Jan 1, 1970. In Python date is not a built-in datatype, the datetime Module is used to manipulate Date and Time.

Читайте также:  Понизить версию php storm

To convert Python Unix epoch/timestamp to datetime, Let us understand how to get Unix current Timestamp/epoch.

How to get Python current Timestamp/epoch?

  • Get the current date and time using datetime.now() Method.
  • Get the Timestamp/epoch from datetime using timestamp() method.
  • Convert timestamp to timestamp milliseconds by multiple 1000

In Our all examples, we are using the hard code value of epoch time. If you need to use the dynamic value of the timestamp, then use the one that we have calculated in the given below example.

Some format code in Python

  • %Y : four-digit year
  • %y : two digit year
  • %m: Month
  • %d: date
  • %H : for hours
  • %M : for minutes
  • %S: for second
  • %f : for milliseconds

Program to Get Python current epoch/timestamp from datetime

from datetime import datetime timestamp = datetime.now().timestamp() print("current timestamp =", timestamp) print("datetime to epoch millisecond:",timestamp*1000)

Program Example

from datetime import datetime unix_timestamp = datetime.now().timestamp() # Getting date and time in local time datetime_obj = datetime.fromtimestamp(int(unix_timestamp)) print('DateTime default Format :',datetime_obj) print('Custome formatted DateTime:',datetime_obj.strftime("%d.%m.%y %H:%M:%S"))
DateTime default Format : 2021-07-31 06:04:52 31.07.21 06:04:52

2. Python epoch/timestamp to dateTime with UTC

In this example, the Datetime module’s utcfromtimestamp() function is used to get the epoch time to datetime with UTC.Finally, The datetime class strftime() method is used to convert datetime to a specific format as per need.

Program to epoch time to dateTime with UTC

from datetime import datetime unix_timestamp = "1627671140" # Getting the date and time in UTC datetime_obj = datetime.utcfromtimestamp(int(unix_timestamp)) print(datetime_obj.strftime("%d.%m.%y %H:%M:%S"))

3. Python epoch/Timestamp milleseconds to Datetime

In this example, we are repeating the same steps as mentioned in the above examples. We are converting Python epoch milliseconds to Datetime.

Читайте также:  Php what url was requested

Program Example

#Python 3 Progaram to epoch milleseconds to Datetime millesecods import datetime millseconds = 1627673330000/ 1000.0 datetime_obj = datetime.datetime.fromtimestamp(millseconds).strftime('%Y-%m-%d %H:%M:%S.%f') print(datetime_obj)

4. Python unix timestamp/epoch to datetime string

Using Datetime module fromtimestamp() function to convert epoch time/Unix timestamp to datetime and strftime() function to convert datetime to string.

Program Example

import datetime unix_time = 1627675321 datetime_obj = datetime.datetime.fromtimestamp(unix_time ).strftime('%Y-%m-%d %H:%M:%S') print(datetime_obj) print(type(datetime_obj))

5. Time Module to Unix timestamp to datetime string

The Python time module strftime() function is used in this example to convert unix timestamp/epoch to datetime.

The first parameter to this function is format code and another is the Unix timestamp.

Program Example

#Python3 program to convert unix timestamp to datetime string import time time_epoch = 1627675321 time_obj = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_epoch)) print("epoch to datetime string:", time_obj) print(type(time_obj))

epoch to datetime string: 2021-07-31 01:32:01

6. Unix timestamp to datetime Python Pandas

In this example, we are using the Pandas module to convert Unix timestamp to datetime.

First, import the panda’s module using import pandas as pd. Then using the pandas to_datetime() function to convert Unix timestamp/epoch to datetime. Finally printing the result using the print() method.

Program Example

import pandas as pd time_epoch = 1627675321 print('unix timestamp to datetime:',pd.to_datetime(time_epoch, unit='s'))
unix timestamp to datetime : 2021-07-30 20:02:01

Summary

  • In this post, we have learned how to convert Unix Timestamp to datetime in Python.First we get the current epoch/timestamp .
  • Then explained with different ways that includes Convert Python epoch to datetime,Python epoch/Timestamp milleseconds to Datetime milliseconds,Python unix timestamp/epoch to datetime string using datetime module fromtimestamp() and strftime() method to datetime.

Источник

Работа с unix timestamp/time на python

Совсем недавно, я начал свое изучение python. Мне потребовалось несколько дней для того чтобы начать писать на нем элементарные вещи. И мне бы хотелось сохранять полезную информацию в виде своих заметок и для питон.

Как преобразовать unix timestamp в datetime на Python?

Делается это очень просто:

#!/bin/env python3 import datetime timestamp = 1339521878.04 value = datetime.datetime.fromtimestamp(timestamp) print(value.strftime('%Y-%m-%d %H:%M:%S'))

Чтобы получить datetime времени (сейчас), можно выполнить:

#!/bin/env python3 import datetime,time dt = datetime.datetime.now() value = datetime.datetime.fromtimestamp(time.mktime(dt.timetuple())) print(value.strftime('%Y-%m-%d %H:%M:%S'))

Как преобразовать datetime в timestamp на Python?

Делается это очень просто:

#!/bin/env python3 from datetime import datetime import time # time tuple in local time to timestamp time_tuple = (2017, 11, 12, 13, 59, 27, 2, 317, 0) timestamp = time.mktime(time_tuple) print (repr(timestamp)) # time tuple in utc time to timestamp time_tuple_utc = (2017, 11, 12, 13, 59, 27, 2, 317, 0) timestamp_utc = calendar.timegm(time_tuple_utc) print (repr(timestamp_utc))
#!/bin/env python3 from datetime import datetime import time # datetime object to string dt_obj = datetime(2017, 11, 10, 17, 53, 59) date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S") print (date_str) # time tuple to string time_tuple = (2017, 11, 12, 13, 51, 18, 2, 317, 0) date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple) print (date_str)
#!/bin/env python3 from datetime import datetime import time # time tuple to datetime object time_tuple = (2017, 11, 12, 13, 51, 18, 2, 317, 0) dt_obj = datetime(*time_tuple[0:6]) print (repr(dt_obj)) # date string to datetime object date_str = "2017-11-10 17:53:59" dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") print (repr(dt_obj)) # timestamp to datetime object in local time timestamp = 1226527167.595983 dt_obj = datetime.fromtimestamp(timestamp) print (repr(dt_obj)) # timestamp to datetime object in UTC timestamp = 1226527167.595983 dt_obj = datetime.utcfromtimestamp(timestamp) print (repr(dt_obj))
datetime.datetime(2017, 11, 12, 13, 51, 18) datetime.datetime(2017, 11, 10, 17, 53, 59) datetime.datetime(2008, 11, 12, 23, 59, 27, 595983) datetime.datetime(2008, 11, 12, 21, 59, 27, 595983)
#!/bin/env python3 from datetime import datetime import time # datetime object to time tuple dt_obj = datetime(2017, 11, 10, 17, 53, 59) time_tuple = dt_obj.timetuple() print (repr(time_tuple)) # string to time tuple date_str = "2017-11-10 17:53:59" time_tuple = time.strptime(date_str, "%Y-%m-%d %H:%M:%S") print (repr(time_tuple)) # timestamp to time tuple in UTC timestamp = 1226527167.595983 time_tuple = time.gmtime(timestamp) print (repr(time_tuple)) # timestamp to time tuple in local time timestamp = 1226527167.595983 time_tuple = time.localtime(timestamp) print (repr(time_tuple))
time.struct_time(tm_year=2017, tm_mon=11, tm_mday=10, tm_hour=17, tm_min=53, tm_sec=59, tm_wday=4, tm_yday=314, tm_isdst=- 1) time.struct_time(tm_year=2017, tm_mon=11, tm_mday=10, tm_hour=17, tm_min=53, tm_sec=59, tm_wday=4, tm_yday=314, tm_isdst=- 1) time.struct_time(tm_year=2008, tm_mon=11, tm_mday=12, tm_hour=21, tm_min=59, tm_sec=27, tm_wday=2, tm_yday=317, tm_isdst=0 ) time.struct_time(tm_year=2008, tm_mon=11, tm_mday=12, tm_hour=23, tm_min=59, tm_sec=27, tm_wday=2, tm_yday=317, tm_isdst=0 )

Источник

Python timestamp to string – Python: How to convert a timestamp string to a datetime object using datetime.strptime()

Python- How to convert a timestamp string to a datetime object using datetime.strptime()

Python timestamp to string: In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.

String to a DateTime object using datetime.strptime()

Python convert timestamp to string: The strptime() method generates a datetime object from the given string.

Datetime module provides a datetime class that has a method to convert string to a datetime object.

Syntax:

datetime.strptime(date_string, format)

So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.

First import datetime class from datetime module to use this,

from datetime import datetime

Complete Format Code List

How strptime() works?

In the strptime() class method, it takes two arguments:

In the accordance with the string and format code used, the method returns its equivalent datetime object.

Let’s see the following example, to understand how it works:

python strptime method example

%d – Represents the day of the month. Example: 01, 02, …, 31
%B – Month’s name in full. Example: January, February etc.
%Y – Year in four digits. Example: 2018, 2019 etc.

Examples of converting a Time String in the format codes using strptime() method

Timestamp to string python: Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.

Example 1:

from datetime import datetime datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f') print(datetimeObj) print(type(datetimeObj))

So in the above example, you can see that we have converted a time string in the format “YYYY-MM-DDTHH::MM::SS.MICROS” to a DateTime object.

Let’s take another example,

Example 2:

from datetime import datetime datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S') print(datetimeObj) print(type(datetimeObj))

So this is the other way to show timestamp here we have converted a time string in the format “DD/MM/YYYY HH::MM::SS” to a datetime object.

Example 3:

If we want to show the only date in this format “DD MMM YYYY”. We do like this,

from datetime import datetime datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y') # Get the date object from datetime object dateObj = datetimeObj.date() print(dateObj) print(type(dateObj))

Example 4:

So if we want to show only time “‘HH:MM:SS AP‘” in this format. We will do like that,

from datetime import datetime datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') # Get the time object from datetime object timeObj = datetimeObj.time() print(timeObj) print(type(timeObj))

Example 5:

If we want to show our timestamp in text format. We will execute like that,

from datetime import datetime textStr = "On January the 17th of 2021 meet me at 8 PM" datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p") print(datetimeObj)

Conclusion:

So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!

Источник

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