如何从utcnow中提取日,月和年?

时间:2017-11-07 13:31:20

标签: python python-3.x

我有以下var:time_created = datetime.utcnow()

如何从time_created_day创建仅包含Y,M,d的time_created变量

喜欢这个datetime.datetime(2017, 11, 7)

我有以下解决方案:

from datetime import date

time_created_day = date(time_created.year, time_created.month, time_created. day)

这是最好的方式吗?

3 个答案:

答案 0 :(得分:2)

使用datetime.utcnow().date()

datetime.utcnow().date()
datetime.date(2017, 11, 7)


添加回答

datetime对象始终包含年,月,日以及小时,分钟,秒和微秒。它是日期和时间对象包含的内容的组合,请参阅datetime Objects

from datetime import datetime

# this is your datetime object
time_created = datetime.utcnow()

# when you want to see it formatted as Y,M,D call the date method
date_created = time_created.date()

time_created
date_created

输出:

datetime.datetime(2017, 11, 7, 23, 43, 43, 761750)
datetime.date(2017, 11, 7)`

答案 1 :(得分:0)

使用time_created.day查找当天。

time_created_day = time_created.day

(月和年类似)

答案 2 :(得分:0)

这里对你来说最简单

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate = year + " " + month + " " + day;