How do I turn a python datetime into a string, with readable format date?
The datetime class has a method strftime. The Python docs documents the different formats it accepts:
- Python 2: strftime() Behavior
- Python 3: strftime() Behavior
For this specific example, it would look something like:
Here is how you can accomplish the same using python’s general formatting function.
The formatting characters used here are the same as those used by strftime. Don’t miss the leading : in the format specifier.
Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated.
How to convert date object to string in C#?
Here you will learn how to convert a DateTime object to a string in C#.
The DateTime struct includes the following methods that return date and time as a string.
| Method | Description |
|---|---|
| DateTime.ToString() | Converts a DateTime value to a string in the specified format of the current culture. |
| DateTime.ToShortDateString() | Converts a DateTime value to a short date string (M/d/yyyy pattern) in the current culture. |
| DateTime.ToShortTimeString() | Converts a DateTime value to a short time string (h:mm:ss pattern) in the current culture. |
| DateTime.ToLongDateString() | Converts a DateTime value to a long date string (dddd, MMMM d, yyyy pattern) in the current culture. |
| DateTime.ToLongTimeString() | Converts a DateTime value to a long time string (h:mm:ss tt pattern) in the current culture. |
Convert DateTime to String using the ToString() Method
Use the DateTime.ToString() method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.ShortDatePattern property associated with the current thread culture. For example, the culture on your local/server environment is set to en-US , then you will get the string value of a date in MM/DD/YYYY format using any of the above methods.
The following converts the date portion of a DateTime object into a string.
In the above example, the ToString() method converts a date to a string based on the DateTimeFormatInfo.ShortDatePattern property of the current thread culture by default.
Convert DateTime to String in Specific Format
You can specify the specific date and time formats in the ToString() method to get a date and time string into a particular format. The following example demonstrates getting date value as a string in different formats using the ToString() method.
Visit date and time format specifiers to know all the format specifiers that can be used with the ToString() method.
Convert DateTime to Date String
Use the ToShortDateString() or ToLongDateString() to get the string of date portion in a short or long format based on your local culture, as shown below.
The ToShortDateString() method uses the ShortDatePattern and the ToLongDateString() method uses the LongDatePattern property property associated with the current thread culture.
Convert DateTime to Time String
Use the ToShortTimeString() or ToLongTimeString() to get the string of time portion in a short or long format based on your local culture, as shown below.
The ToShortTimeString() method uses the pattern defined by the ShortTimePattern property and the ToLongTimeString() method uses the LongTimePattern property associated with the current thread culture.
Conclusion
Use the ToString() method to convert a date object to different formats as per your need. Use ToShortDateString() or ToShortTimeString() to get short date and time string. Use ToLongDateString() or ToLongTimeString() to get the date and time in long format.
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
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.
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
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
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
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
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.
Table of DateTime format code in Python
These are list of format code available in Python as per python docs
| 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.
Дата и время в Питоне
Говоря про временные ряды, мы уже начали анализировать данные, в которых присутствует дата и время (в частности, в библиотеке Pandas). Сегодня мы сделаем шаг назад и посмотрим в целом как работать с датой и временем в Питоне.

Модуль datetime
В базовом функционале Питона нет отдельного типа данных, отвечающего за дату и время. Необходимо импортировать модуль, который называется datetime.
Первая особенность, про которую стоит сказать, datetime — это не только название модуля, но и название одного из классов внутри этого модуля. Помимо класса datetime, нас будет интересовать ещё один класс — timedelta.

Перейдем к практике.
Импорт модуля и класса datetime
Самый простой способ — импортировать весь модуль datetime.
Далее предположим, что мы хотим воспользоваться функцией now(), которая находится внутри класса datetime. Функция now() выводит текущие дату и время.
Как вы видите, это не очень удобно. Можно импортировать только класс datetime и обращаться непосредственно к нему.
Объект datetime и функция now()
Теперь поговорим подробнее про то, что выводит функция now().
На выходе мы получаем текущие дату и время по UTC⧉, потому что серверы Google Colab настроены именно на это время (московское время, например, отличается на +3 часа). Сам вывод состоит из следующих компонентов.

Мы можем обратиться к каждому из этих компонентов по отдельности.
Мы также можем посмотреть на день недели, причем в двух форматах. Метод .weekday() считает, что неделя начинается с нуля, метод .isoweekday(), что с единицы.

Так как 18 ноября 2021 года — это четверг, то применив эти методы, мы должны получить цифры три и четыре соответственно.
Разумеется, когда вы будете самостоятельно исполнять код в ноутбуке, будут выведены текущие дата и время сервера Google.
Объект datetime, полученный из функции now(), не содержит данных о часовом поясе.
Для того чтобы добавить такую информацию и вывести, например, другой часовой пояс, нам нужно воспользоваться модулем pytz.
Посмотрим, не появился ли часовой пояс.
Timestamp
До сих пор мы работали с привычным для нас делением на годы, месяцы, дни, часы, минуты и секунды. При этом компьютеры используют так называемое время Unix, которое отсчитывается в секундах c первого января 1970 года. Для отображения даты и времени в таком формате в Питоне есть объект timestamp (по-английски — «временная отметка»).
Посмотрим, сколько секунд и микросекунд прошло с 01.01.1970 и до момента исполнения кода.
Не составляет труда вернуть timestamp обратно в привычный формат.
Создание объекта datetime вручную
Дату и время не обязательно получать из функции now(). Мы вполне можем передать объекту datetime наши собственные параметры, например, день рождения Питона.
Обратите внимание, мы ввели только год, месяц и день. Это обязательные параметры. Остальные параметры можно не вводить, в этом случае они заполнятся нулями.
Из этого объекта мы также можем извлечь компоненты (год, месяц, число и т.д.) и создать timestamp.
Преобразование строки в datetime и наоборот
Строка в datetime через .strptime()
Если дата содержится в строковом формате, Питон не сможет извлечь из нее компоненты. Предварительно строку нужно преобразовать. Для этого есть метод .strptime().
Преобразуем эту строку в объект datetime с помощью метода .strptime().
Как вы видите, сначала мы передаём этому методу саму строку, а затем тот формат, в котором содержится дата и время (иначе Питон не поймет, к чему относится конкретное число).
Давайте расшифруем каждое из обозначений:
- % Y — год в формате ГГГГ, например: 1995, 2003 и т.д.
- % m — месяц в виде числа с нулями, например, январь — 01, февраль — 02 и т.д.
- % d — день месяца в виде числа с нулями, например: 01, 02, …, 31
- % H — час в 24-часовом формате в виде числа с нулями, например: 00, 01, …, 23
- % M — минуты в виде числа с нулями, например: 00, 01, …, 59
- % S — секунды в виде числа с нулями, например: 00, 01, …, 59
Дефисы, пробелы, двоеточия или, например, запятые — тоже элементы формата и их тоже нужно указывать.
Datetime в строку через .strftime()
Обратное преобразование также возможно. Это может быть полезно, если мы захотим вывести дату и время в строго определенном формате.