如何更改日期字符串格式(2052年10月20日-> 2052-10-20) [英] How to change Date String Format (20th Oct 2052 -> 2052-10-20)

查看:58
本文介绍了如何更改日期字符串格式(2052年10月20日-> 2052-10-20)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Blockquote

Blockquote

我有一个日期字符串,格式为Day Month Year,例如1984年3月1日,1973年4月4日,2006年5月22日,其中:

I have a date string in the format Day Month Year, like 1st Mar 1984, 4th Apr 1973, 22nd May 2006, where:

日期位于集合{"1st","2nd","3rd",...,'"30th","31st"}}

Day is in the set {"1st","2nd","3rd",...,'"30th","31st"}

月份在集合{"Jan","Feb","Mar",...,"Dec"}中

Month is in the set {"Jan","Feb","Mar",...,"Dec"}

年份在[1900,2100]范围内

Year is in the range [1900,2100]

我必须将日期字符串转换为YYYY-MM-DD格式,例如:1984年3月1日-> 1984-03-011973年4月4日-> 1973-04-04

I gotta convert the date string to the format YYYY-MM-DD, like: 1st Mar 1984 -> 1984-03-01 4th Apr 1973 -> 1973-04-04

(函数ReformatDate具有以下参数:date [dates [0],...,dates [n-1]]是日期字符串数组,格式为Day Month Year)

(The function reformatDate has the following parameters: dates[dates[0],...,dates[n-1]] is an array of date strings in the format Day Month Year)

样本输入42052年10月20日1933年6月6日1960年5月26日1958年9月20日

Sample Input 4 20th Oct 2052 6th Jun 1933 26th May 1960 20th Sep 1958

示例输出2052-10-201933-06-061960-05-261958-09-20

Sample Output 2052-10-20 1933-06-06 1960-05-26 1958-09-20

enter code here
    def reformatDate(dates):
    # write your code here
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
        dates_count = int(input().strip())
        dates = []
        for _ in range(dates_count):
            dates.item = input()
            dates.append(dates_item)       
        result = reformatDate(dates)
        fptr.write('\n'.join(result))
        fptr.write('\n')
        fptr.close

推荐答案

这是使用 datetime 模块的一种方法.

This is one approach using datetime module.

例如:

import datetime
import re    

lst = ["20th Oct 2052", "6th Jun 1933", "26th May 1960", "20th Sep 1958"]
for i in lst:
    print(datetime.datetime.strptime(re.sub(r"(st|th|rd)", "", i), "%d %b %Y").strftime("%Y-%m-%d"))

输出:

2052-10-20
1933-06-06
1960-05-26
1958-09-20

注意: re.sub(r(st | th | rd)",",i)从日期中删除st,th,rd.

Note: re.sub(r"(st|th|rd)", "", i) to remove st, th, rd from date.

这篇关于如何更改日期字符串格式(2052年10月20日-> 2052-10-20)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆