python中时间日期格式化符号_在Python中格式化1900之前的日期字符串?

每400年的日历都是一样的。因此,在调用datetime.strftime()之前,将year更改为400的倍数就足够了。在

代码显示了这种方法存在的问题:#/usr/bin/env python2.6

import re

import warnings

from datetime import datetime

def strftime(datetime_, format, force=False):

"""`strftime()` that works for year < 1900.

Disregard calendars shifts.

>>> def f(fmt, force=False):

... return strftime(datetime(1895, 10, 6, 11, 1, 2), fmt, force)

>>> f('abc %Y %m %D')

'abc 1895 10 10/06/95'

>>> f('%X')

'11:01:02'

>>> f('%c') #doctest:+NORMALIZE_WHITESPACE

Traceback (most recent call last):

ValueError: '%c', '%x' produce unreliable results for year < 1900

use force=True to override

>>> f('%c', force=True)

'Sun Oct 6 11:01:02 1895'

>>> f('%x') #doctest:+NORMALIZE_WHITESPACE

Traceback (most recent call last):

ValueError: '%c', '%x' produce unreliable results for year < 1900

use force=True to override

>>> f('%x', force=True)

'10/06/95'

>>> f('%%x %%Y %Y')

'%x %Y 1895'

"""

year = datetime_.year

if year >= 1900:

return datetime_.strftime(format)

# make year larger then 1900 using 400 increment

assert year < 1900

factor = (1900 - year - 1) // 400 + 1

future_year = year + factor * 400

assert future_year > 1900

format = Specifier('%Y').replace_in(format, year)

result = datetime_.replace(year=future_year).strftime(format)

if any(f.ispresent_in(format) for f in map(Specifier, ['%c', '%x'])):

msg = "'%c', '%x' produce unreliable results for year < 1900"

if not force:

raise ValueError(msg + " use force=True to override")

warnings.warn(msg)

result = result.replace(str(future_year), str(year))

assert (future_year % 100) == (year % 100) # last two digits are the same

return result

class Specifier(str):

"""Model %Y and such in `strftime`'s format string."""

def __new__(cls, *args):

self = super(Specifier, cls).__new__(cls, *args)

assert self.startswith('%')

assert len(self) == 2

self._regex = re.compile(r'(%*{0})'.format(str(self)))

return self

def ispresent_in(self, format):

m = self._regex.search(format)

return m and m.group(1).count('%') & 1 # odd number of '%'

def replace_in(self, format, by):

def repl(m):

n = m.group(1).count('%')

if n & 1: # odd number of '%'

prefix = '%'*(n-1) if n > 0 else ''

return prefix + str(by) # replace format

else:

return m.group(0) # leave unchanged

return self._regex.sub(repl, format)

if __name__=="__main__":

import doctest; doctest.testmod()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值