Date from timestamp python

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

In this article we will discuss how to convert timestamp in different string formats to a datetime class object in Python.

String to datetime object using datetime.strptime()

Python’s datetime module provides a datetime class, which has a method to convert string to a datetime object i.e.

datetime.strptime(date_string, format)

If accepts a string containing the timestamp and a format string containing the format codes representing the date time elements in date_string. It parses the string according to format codes and returns a datetime object created from it.

To use this import datetime class from datetime module i.e.

Frequently Asked:

from datetime import datetime

Example 1:

Let’s convert a time string in format YYYY-MM-DDTHH::MM::SS.MICROS to a datetime object i.e.

datetimeObj = datetime.strptime('2018-09-11T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f') print(datetimeObj) print(type(datetimeObj))

Format string used here is : ‘%Y-%m-%dT%H::%M::%S.%f

Complete list of format code :

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y Year without century as a zero-padded decimal number 00, 01, …, 99
%Y Year with century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM , PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366
Читайте также:  Python скрипт для linux

Let’s see some other examples :

Example 2:

Let’s convert a timestamp string in format DD/MM/YYYY HH::MM::SS to a datetime object i.e.

datetimeObj = datetime.strptime('23/Jan/2018 14:12:22', '%d/%b/%Y %H:%M:%S') print(datetimeObj)

Example 3:

Create Date Time Object from date string only in ‘DD MMM YYYY‘ format

datetimeObj = datetime.strptime('29 Oct 2018', '%d %b %Y') # Get the date object from datetime object dateObj = datetimeObj.date() print(dateObj) print(type(dateObj))

Example 4:

Create datetime Object from time string only in ‘HH:MM:SS AP‘ format

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

Example 5:

Create datetime Object from timestamp scattered in a text.

Some time our timestamp is embedded in a text like,

"On January the 5th of 2018 meet me at 5 PM"

Let’s see how to convert timestamp in this string to a date time object with format codes mixed in text i.e.

textStr = "On January the 5th of 2018 meet me at 5 PM" datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p") print(datetimeObj)

Complete example is as follows,

from datetime import datetime def main(): print("*** Convert timestamp String of format 'YYYY-MM-DDTHH::MM::SS.MICROS' to date time object ***") datetimeObj = datetime.strptime('2018-09-11T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f') print(datetimeObj) print(type(datetimeObj)) print("*** Convert timestamp String of format 'DD/MM/YYYY HH:MM:SS' to date time object ***") # Convert String of format 'DD/MM/YYYY HH:MM:SS' to date time object datetimeObj = datetime.strptime('23/Jan/2018 14:12:22', '%d/%b/%Y %H:%M:%S') print(datetimeObj) print("*** Create DateTime Object from date string only in 'DD MMM YYYY' format ***") datetimeObj = datetime.strptime('29 Oct 2018', '%d %b %Y') # Get the date object from datetime object dateObj = datetimeObj.date() print(dateObj) print(type(dateObj)) print("*** Create DateTime Object from time string only in 'HH:MM:SS AP' format ***") datetimeObj = datetime.strptime('05:12:22 PM', '%I:%M:%S %p') # Get the time object from datetime object timeObj = datetimeObj.time() print(timeObj) print(type(timeObj)) print('*** Create DateTime Object from timestamp scattered in a text ***') textStr = "On January the 5th of 2018 meet me at 5 PM" datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p") print(datetimeObj) if __name__ == '__main__': main()
*** Convert timestamp String of format 'YYYY-MM-DDTHH::MM::SS.MICROS' to date time object *** 2018-09-11 15:11:45.456777 *** Convert timestamp String of format 'DD/MM/YYYY HH:MM:SS' to date time object *** 2018-01-23 14:12:22 *** Create DateTime Object from date string only in 'DD MMM YYYY' format *** 2018-10-29 *** Create DateTime Object from time string only in 'HH:MM:SS AP' format *** 17:12:22 *** Create DateTime Object from timestamp scattered in a text *** 2018-01-05 17:00:00

Источник

How To Convert Timestamp To Date and Time in Python

There are multiple ways how you can convert timestamp to human readable form in Python. For this conversion you may either use module datetime or time.

Using module datetime

Module datetime provides classes for manipulating date and time in more object oriented way.

 import datetime readable = datetime.datetime.fromtimestamp(1689777031).isoformat() print(readable) # 2023-07-19T16:30:31+02:00

Using module time

Another possibility to use function ctime from module time .

 import time readable = time.ctime(1689777031) # Wed Jul 19 16:30:31 2023

Formatting

For custom human readable format you may use function strftime .

 import time ts = time.gmtime() print(time.strftime("%Y-%m-%d %H:%M:%S", ts)) # 2023-07-19 16:30:31 print(time.strftime("%x %X", ts)) # 07/19/23 16:30:31 # Iso Format print(time.strftime("%c", ts)) # Wed Jul 19 16:30:31 2023 # Unix timestamp print(time.strftime("%s", ts)) # 1689777031 
Directive Meaning
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal ‘%’ character.

Tags

Источник

Python timestamp to datetime and vice-versa

It’s pretty common to store date and time as a timestamp in a database. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC.

We can simply use the fromtimestamp() method from the datetime module to get a date from a UNIX timestamp.

Python timestamp to datetime

from datetime import datetime # timestamp is number of seconds since 1970-01-01 timestamp = 1545730073 # convert the timestamp to a datetime object in the local timezone dt_object = datetime.fromtimestamp(timestamp) # print the datetime object and its type print("dt_object =", dt_object) print("type(dt_object) line-highlight">

Output

dt_object = 2018-12-25 09:27:53 type(dt_object) =

Here, we have imported the datetime class from the datetime module.

Then, we used the datetime.fromtimestamp() class method which returns the local date and time (datetime object). This object is stored in the dt_object variable.

Note: We can easily create a string representing date and time from a datetime object using strftime() method.

Python datetime to timestamp

In Python, we can get timestamp from a datetime object using the datetime.timestamp() method. For example,

from datetime import datetime # current date and time now = datetime.now() # convert from datetime to timestamp ts = datetime.timestamp(now) print("Timestamp tutorial-toc">

Table of Contents

Источник

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