Python get date to string

How to convert DateTime to string in Python

In this post, we are going to learn how to convert DateTime to string in Python using different code examples. To get the date in a different format in Python we use strftime(),format() functions and f-string.We will learn about all these functions in this post.

Python Strftime() Function

The datetime class has a member function strftime(). The strftime() function of the DateTime class takes two arguments in which the first argument is the string representation of datetime and the second is the format of the input string.

Syntax

datetime.strftime(Format_String)

Steps to convert DateTime to string in Python

  • We need to import datetime module in our program and after that we can use the strftime() and format() functions to convert a datetime object to string in Python.
  • We can choose datetime to string formats as per our requirement by using format codes given in below table at the end of this article.
Читайте также:  Javascript minutes to days

1. How how to convert DateTime to string in Python using strftime()

In this example, we are converting datetime to string in the format of DD-MMM-YYYY HH:MM:SS using the strftime() function.

Program Example

from datetime import datetime dt_obj = datetime.now() dt_to_text = dt_obj.strftime("All are informed that\n %A %d %B %Y is board metting at : %I:%M %p") print(time_to_Str )
All are informed that Wednesday 21 July 2021 is board metting at : 12:33 AM

3. Convert Python date to string

Sometime instead of datetime we need to convert only Python date to string in different formats. In this example we are converting Python date only to differnt string formats.

Program Example

from datetime import datetime dt_obj = datetime.now() #Date Month Year Date_to_str = dt_obj.strftime("%d %b, %Y") print("dd/mm/year:", Date_to_str) #Full Textual month name, day and year Dt_st_Frmt = dt_obj.strftime("%B %d, %Y") print("month name/day/year :", Dt_st_Frmt) #mm/dd/yyyy dt_frt = dt_obj.strftime("%m/%d/%Y") print("mm/dd/yyyy:",dt_frt )
dd/mm/year: 20 Jul, 2021 month name/day/year : July 20, 2021 mm/dd/yyyy: 07/20/2021

4. Convert Python Time to string

Sometimes we need to convert Python time into different string formats as we are doing in the below example.

Program Example

from datetime import datetime dt_obj = datetime.now() time_to_Str = dt_obj.strftime("%H:%M:%S.%f") print("hh:mm:ss:ms =",time_to_Str )

5. Using format() function

The format() function can be used to convert datetime to different string formats. It is provided with curly brackets followed by a colon mark.

Program example

from datetime import datetime dt_obj = datetime.now() print('Day/mm/dd/yyyy : ', ''.format(dt_obj)) print('mm/dd/yyyy : ', ''.format(dt_obj)) print('mm/dd/yy hh:mm:ss : ',''.format(dt_obj)) print('mm/dd/yy hh:mm:ss:ms : ' ,''.format(dt_obj))
Day/mm/dd/yyyy : Wed, July 21 2021 mm/dd/yyyy : 07/21/2021 mm/dd/yy hh:mm:ss : 07/21/21 09:05 08 mm/dd/yy hh:mm:ss:ms : 07/21/21 09:05 08 993077

6. How to convert DateTime to string in Python sing f-string

By using f-string, the datetime can be converted into different string formats. The f-string is evaluated at run-time. We can use any valid Python expression in them.

from datetime import datetime dt_obj = datetime.now() dt_to_str = f'The date to string is mm/dd/yyyy : ' dt_to_str1 = f'The date to string mm/dd/yy hh:mm:ss:ms: ' print(dt_to_str) print(dt_to_str1)
The date to string is mm/dd/yyyy : Jul 21, 2021 The date to string mm/dd/yy hh:mm:ss:ms: 07/21/21 17:36 32

Table of DateTime format code in Python

These are list of format code available in Python as per python docs

Читайте также:  Python глобальные переменные между модулями
Format codes Description Example
%a Weekday as the abbreviated name Sun, Mon, …, Sat
%A Weekday as locale’s full name Sunday,…Saturday
%w Weekday as a decimal number, 0 is Sunday,6 is Saturday. 0, 1, …, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec
%m Month as a zero-padded decimal number. 01, 02, …, 12
%B Month as locale’s full name. January, February.
%y Year without century 00, 01, …, 99
%Y Year with century 0001, 0002, …, 9998, 9999
%H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
%p Locale’s equivalent of either AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%s The second is a zero-padded decimal number. 00, 01, …, 59
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999

Summary

In this post, we have learned different ways of How to convert DateTime to string in Python with code example by Using strftime(), format() functions. We can change the datetime to string format as per our requirment using any of both methods by passing format code as given in above table.

Источник

Python datetime to String

In this article, you will learn how to convert datetime to string in Python. You will understand the need for conversion and everything around it.

In python, datetime is an object (returned by datetime module) that represents a date and time . It stores information like year, month, day, hour, minute, second, microsecond, and timezone.

The informations are extracted from the datetime object using the strftime() method of the datetime object.

When printed the datetime object, it returns a string in the format YYYY-MM-DD HH:MM:SS.mmmmmm and has the type of .

python datetime to string

Let’s look at how we can extract different informations from a given datetime object and display it in different string formats.

Using strftime() method

strftime() is a method of datetime class in datetime module. It is used to convert datetime object to string.

strftime Method

To use strftime() method, you need to import datetime module.

It accepts a format string as an argument and returns a string representing the date and time using that format.

import datetime as dt # get current date and time now = dt.datetime.now() # convert to string now_string = now.strftime("%d/%m/%Y %H:%M:%S") print(now_string)

Here is another example to show the date in format January 1, 2021 .

import datetime as dt # get current date and time now = dt.datetime.now() # convert to string now_string = now.strftime("%B %d, %Y") print(now_string)

Characters used in the above code like %A , %B , %d , %Y are called format directives. They are used to represent different parts of date and time.

Format Directives

Format directives are codes that are used to represent different parts of datetime object.

It is represented by a % sign followed by a character. The character represents the part of the date and time that you want to express.

Here is the list of all the format directives that can be used with strftime() method.

Directive Description Example
%a Abbreviated weekday name Sun, Mon, . Sat
%A Full weekday name Sunday, Monday, . Saturday
%b Abbreviated month name Jan, Feb, . Dec
%B Full month name January, February, . December
%c Locale’s date and time representation Tue Mar 27 11:45:40 2018
%d Day of the month as a zero-padded decimal number 01, 02, . 31
%H Hour (24-hour clock) as a zero-padded decimal number 00, 01, . 23
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, . 12
%j Day of the year as a zero-padded decimal number 001, 002, . 366
%m Month as a zero-padded decimal number 01, 02, . 12
%M Minute as a zero-padded decimal number 00, 01, . 59
%p Locale’s equivalent of AM or PM AM, PM
%S Second as a zero-padded decimal number 00, 01, . 59
%U Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number 00, 01, . 53
%w Weekday as a decimal number (0 is Sunday) 0, 1, . 6
%W Week number of the year (Monday as the first day of the week) as a zero-padded decimal number 00, 01, . 53
%x Locale’s date representation 03/27/18
%X Locale’s time representation 10:24:55
%y Year without century as a zero-padded decimal number 00, 01, . 99
%Y Year with century as a decimal number 0001, 0002, . 2018, 2019, . 9998, 9999
%z UTC offset in the form +HHMM or -HHMM +0000, -0400, +1030
%Z Time zone name (empty string if the object is naive) (empty), UTC, EST, CST
%% A literal ‘%’ character %

Here is an example that shows individual components of a datetime object.

import datetime as dt # get current date and time now = dt.datetime.now() # individual components year = now.year month = now.month day = now.day hour = now.hour minute = now.minute second = now.second print("Year: ", year) print("Month: ", month) print("Day: ", day) print("Hour: ", hour) print("Minute: ", minute) print("Second: ", second)
Output: Year: 2018 Month: 3 Day: 27 Hour: 10 Minute: 24 Second: 55

Example: Python datetime to string format

Let’s see different kinds of examples to convert datetime to string format.

Example 1

Converting datetime object to string in YYYY-MM-DD format.

import datetime as dt # get current date and time now = dt.datetime.now() # format: YYYY-MM-DD now_string = now.strftime("%Y-%m-%d") print(now_string)

Example 2

Converting datetime object to string in YYYY-MM-DD HH:MM:SS format.

import datetime as dt # get current date and time now = dt.datetime.now() # format: YYYY-MM-DD HH:MM:SS now_string = now.strftime("%Y-%m-%d %H:%M:%S") print(now_string)

Example 3

Converting datetime object to string in Month DD, YYYY format.

import datetime as dt # get current date and time now = dt.datetime.now() # format: Month DD, YYYY now_string = now.strftime("%B %d, %Y") print(now_string)

Example 4

Converting datetime object to string in Month DD, YYYY HH:MM:SS format.

import datetime as dt # get current date and time now = dt.datetime.now() # format: Month DD, YYYY HH:MM:SS now_string = now.strftime("%B %d, %Y %H:%M:%S") print(now_string)
Output: March 27, 2018 10:24:55

Example 5

Converting datetime object to string in DD/MM/YYYY format.

import datetime as dt # get current date and time now = dt.datetime.now() # format: DD/MM/YYYY now_string = now.strftime("%d/%m/%Y") print(now_string)

Bonus💰: Timestamp to String Python

Above we have converted datetime object to string. But what if we have a timestamp instead of datetime object?🤔

We can convert timestamp to datetime object and then convert datetime object to string using strftime() method.

import datetime as dt # timestamp timestamp = 1222098295 # convert timestamp to datetime object dt_object = dt.datetime.fromtimestamp(timestamp) # format: Month DD, YYYY HH:MM:SS now_string = dt_object.strftime("%B %d, %Y %H:%M:%S") print(now_string)
Output: September 22, 2008 21:14:55

Conclusion

So, this was all about converting datetime objects to strings in Python. You have gone through multiple examples.

By understanding the concept now you can convert datetime objects and timestamp to strings in any format you want.

Источник

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