Convert datetime object to a String of date only in Python
我在python中将日期字符串转换为
1 | datetime.datetime(2012, 2, 23, 0, 0) |
我想把它转换成类似于
你可以用strftime来帮你安排日期。
例如。,
1 2 3 | import datetime t = datetime.datetime(2012, 2, 23, 0, 0) t.strftime('%m/%d/%Y') |
将产生:
1 | '02/23/2012' |
号
有关格式设置的详细信息,请参见此处
- 直接方法调用:
dt.strftime('format here') ;及 - 新格式方法:
'{:format here}'.format(dt) 。
因此,您的示例可能如下所示:
1 | dt.strftime('%m/%d/%Y') |
。
或
1 | '{:%m/%d/%Y}'.format(dt) |
。
为了完整起见:您还可以直接访问对象的属性,但只能获取数字:
1 | '%s/%s/%s' % (dt.month, dt.day, dt.year) |
学习迷你语言所花费的时间是值得的。
以下是小语言中使用的代码供参考:
%a 工作日作为地区的缩写名称。%a 工作日作为地区的全名。%w 工作日为十进制数,其中0为星期日,6为星期六。- 月份的第1天(9),用零填充的十进制数表示。
%b 个月作为地区的简称。%b 个月作为地区的全名。%m 月为零填充十进制数。01,…,12岁%y 年,无世纪,为零填充十进制数。00,…,99岁- 以世纪为十进制数的江户十一〔13〕年。1970、1988、2001、2013年
%H 小时(24小时制)作为零填充十进制数。00,…,23岁%I 小时(12小时制)为零填充十进制数。01,…,12岁%p 地区相当于上午或下午。%m 分钟,作为零填充十进制数。00,…,59岁%S 秒,作为零填充十进制数。00,…,59岁%f 微秒,十进制数,左边加零。000000,…,999999%z UTC偏移量,格式为+hhmm或-hhmm(幼稚时为空),+0000,-0400,+1030%z 时区名称(幼稚时为空)、UTC、EST、CST- 一年中的某一天(23),用零填充的十进制数表示。001,…,366年
%U 一年中的周数(星期日是第一个),作为零填充的十进制数。- 一年中的第(8)周(星期一是第一个)作为十进制数。
%c 地区的适当日期和时间表示。%x 地区的适当日期表示。%x 区域的适当时间表示。%% 是一个字面"%"字符。
另一种选择:
1 2 3 4 | import datetime now=datetime.datetime.now() now.isoformat() # ouptut --> '2016-03-09T08:18:20.860968' |
您可以使用简单的字符串格式设置方法:
1 2 3 4 5 | >>> dt = datetime.datetime(2012, 2, 23, 0, 0) >>> '{0.month}/{0.day}/{0.year}'.format(dt) '2/23/2012' >>> '%s/%s/%s' % (dt.month, dt.day, dt.year) '2/23/2012' |
也可以使用
1 2 | t = datetime.datetime(2012, 2, 23, 0, 0) "{:%m/%d/%Y}".format(t) |
。
输出:
1 | '02/23/2012' |
号
通过直接使用datetime对象的组件,可以将datetime对象转换为字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from datetime import date myDate = date.today() #print(myDate) would output 2017-05-23 because that is today #reassign the myDate variable to myDate = myDate.month #then you could print(myDate.month) and you would get 5 as an integer dateStr = str(myDate.month)+"/" + str(myDate.day) +"/" + str(myDate.year) # myDate.month is equal to 5 as an integer, i use str() to change it to a # string I add(+)the"/" so now I have"5/" then myDate.day is 23 as # an integer i change it to a string with str() and it is added to the"5/" # to get"5/23" and then I add another"/" now we have"5/23/" next is the # year which is 2017 as an integer, I use the function str() to change it to # a string and add it to the rest of the string. Now we have"5/23/2017" as # a string. The final line prints the string. print(dateStr) |
号
产量——>5/23/2017
可以将日期时间转换为字符串。
1 | published_at ="{}".format(self.published_at) |
。
字符串连接(
1 2 3 | d = datetime.now() '/'.join(str(x) for x in (d.month, d.day, d.year)) '3/7/2016' |
。
如果您想寻找一种简单的从
1 2 3 4 5 6 7 8 9 10 11 12 | In [1]: from datetime import datetime In [2]: now = datetime.now() In [3]: str(now) Out[3]: '2019-04-26 18:03:50.941332' In [5]: str(now)[:10] Out[5]: '2019-04-26' In [6]: str(now)[:19] Out[6]: '2019-04-26 18:03:50' |
号
但要注意以下几点。如果其他解决方案在变量为
1 2 | In [9]: str(None)[:19] Out[9]: 'None' |
号