MyTetra Share
Делитесь знаниями!
Отформатировать дату в Python
Время создания: 04.05.2018 14:58
Автор: br0ke
Текстовые метки: python, date, datetime, output, format, strftime, pendulum, babel, locale, setlocale, localization, localized
Раздел: Информационные технологии - Python
Запись: and-semakin/mytetra_data/master/base/1525423865a912jur9y6/text.html на raw.githubusercontent.com

1) Обычное форматирование (числовое или прописью на английском):

from datetime import datetime


dt = datetime.now()


# 1) str.format

strg = '{:%B %d, %Y}'.format(dt)

print(strg) # July 22, 2017


# 2) datetime.strftime

strg = dt.strftime('%B %d, %Y')

print(strg) # July 22, 2017


# 3) f-strings in python >= 3.6

strg = f'{dt:%B %d, %Y}'

print(strg) # July 22, 2017


2) Представление прописью на русском языке (взято отсюда: https://ru.stackoverflow.com/a/623845):

#!/usr/bin/env python3

import pendulum # $ pip install pendulum


d = pendulum.from_format('01.07.2009', '%d.%m.%Y')

ordinal_day_word = ['', 'первое', 'второе', 'третье', ...][d.day]

print(ordinal_day_word + d.format(' %B %Y года', locale='ru'))

# -> первое июля 2009 года


3) Получить дату в локализированном формате для определенного языка:


>>> import time

>>> print time.strftime("%a, %d %b %Y %H:%M:%S")

Sun, 23 Oct 2005 20:38:56

>>> import locale

>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish

'sv_SE'

>>> print time.strftime("%a, %d %b %Y %H:%M:%S")

sön, 23 okt 2005 20:39:15


Нужно быть внимательным с локалями, потому что на Linux/Unix и Windows они записываются по-разному. Кроме того, команда смены локали глобальна для программы и может поменять поведение в неожиданных местах. Чтобы этого избежать, можно воспользоваться локализирующими библиотеками, типа babel:


>>> from datetime import date, datetime, time

>>> from babel.dates import format_date, format_datetime, format_time


>>> d = date(2007, 4, 1)

>>> format_date(d, locale='en')

u'Apr 1, 2007'

>>> format_date(d, locale='de_DE')

u'01.04.2007'



Code

Meaning

Example

%a

Weekday as locale’s abbreviated name.

Mon

%A

Weekday as locale’s full name.

Monday

%w

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

1

%d

Day of the month as a zero-padded decimal number.

30

%-d

Day of the month as a decimal number. (Platform specific)

30

%b

Month as locale’s abbreviated name.

Sep

%B

Month as locale’s full name.

September

%m

Month as a zero-padded decimal number.

09

%-m

Month as a decimal number. (Platform specific)

9

%y

Year without century as a zero-padded decimal number.

13

%Y

Year with century as a decimal number.

2013

%H

Hour (24-hour clock) as a zero-padded decimal number.

07

%-H

Hour (24-hour clock) as a decimal number. (Platform specific)

7

%I

Hour (12-hour clock) as a zero-padded decimal number.

07

%-I

Hour (12-hour clock) as a decimal number. (Platform specific)

7

%p

Locale’s equivalent of either AM or PM.

AM

%M

Minute as a zero-padded decimal number.

06

%-M

Minute as a decimal number. (Platform specific)

6

%S

Second as a zero-padded decimal number.

05

%-S

Second as a decimal number. (Platform specific)

5

%f

Microsecond as a decimal number, zero-padded on the left.

000000

%z

UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

%Z

Time zone name (empty string if the object is naive).

%j

Day of the year as a zero-padded decimal number.

273

%-j

Day of the year as a decimal number. (Platform specific)

273

%U

Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.

39

%W

Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.

39

%c

Locale’s appropriate date and time representation.

Mon Sep 30 07:06:05 2013

%x

Locale’s appropriate date representation.

09/30/13

%X

Locale’s appropriate time representation.

07:06:05

%%

A literal '%' character.

%

Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования