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)
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'
你可以使用strftime来帮助你格式化你的日期。
例如。
将产生。
更多关于格式化的信息见这里
date
和datetime
对象(还有time
)支持指定输出的迷你语言,有两种方法可以访问它。dt.strftime('format here')
。 和'{:format here}'.format(dt)
。所以你的例子可以是这样的。
或
为了完整性'。 的缘故,你也可以直接访问对象的属性。 你也可以直接访问对象的属性,但是你只能得到数字。
学习小语种所花费的时间是值得的。
以下是迷你语言中使用的代码,供参考。
%a
工作日作为当地的缩写名称。%a
工作日为当地的全称。%w
工作日为十进制数字,其中0为周日,6为周六。%d
每月的某一天,为零填充的十进制数。%b
月份为地区名称的缩写。%B
月份为当地的全称。%m
月份为零填充的小数。 01, ..., 12%y
年,不含世纪,为零填充的十进制数。 00, ..., 99%Y
以世纪为小数的年份。 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。%j
年的哪一天,是一个零填充的十进制数。 001, ..., 366%U
年的周数(周日是第一周)为零垫小数。%W
一年中的星期号(星期一是第一个),为小数。%c
本地的适当的日期和时间表示。%x
本地的适当的日期表示法。%X
本地的适当的时间表示法。%%
一个字面的'%' 字符。另一种选择。
你可以使用简单的字符串格式化方法。
也可以使用
类型特定格式化
。输出。
通过直接使用日期时间对象的组件,可以将日期时间对象转换为字符串。
产出-> 5/23/2017
你可以将日期时间转换为字符串。
字符串连接,
str.join
,可以用来构建字符串。如果你正在寻找一种简单的 "datetime "到字符串的转换方法,并且可以省略格式。 你可以将
datetime
对象转换为str
,然后使用数组切片。但要注意以下几点。 如果其他解决方案会在变量为 "None "时出现 "AttributeError",在这种情况下,你会收到一个"'None' "的字符串。
如果你也想要时间的话,就选择用
在控制台为我打印 "2019-07-11 19:36:31.118766"。