简体   繁体   English

如何在python3上打印当前日期?

[英]How to print current date on python3?

From what I gather, here (for example), this should print the current year in two digits根据我收集的信息,在这里(例如),这应该以两位数打印当前年份

print (datetime.strftime("%y"))

However, I get this error但是,我收到此错误

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

So I tried to this所以我尝试了这个

print (datetime.strftime(datetime.date()))

to get要得到

TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument

so I placed "%y" inside of thr date() above to get所以我在上面的 thr date()中放置了"%y"以获得

TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'str'

Which start to seem really loopy and fishy to me.对我来说,这开始显得非常古怪和可疑。

What am I missing?我错过了什么?

import datetime
now = datetime.datetime.now()

print(now.year)

The above code works perfectly fine for me.上面的代码对我来说非常好。

The following seems to work:以下似乎有效:

import datetime
print (datetime.datetime.now().strftime("%y"))

The datetime.data object that it wants is on the "left" of the dot rather than the right.它想要的 datetime.data 对象位于点的“左侧”而不是右侧。 You need an instance of the datetime to call the method on, which you get through now()您需要一个日期时间的实例来调用该方法,您可以通过 now()

I use this which is standard for every time我每次都使用这个标准

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

The built-in datetime module contains many functions for getting the specific time and date:内置的datetime模块包含许多用于获取特定时间和日期的函数:

from datetime import datetime
from math import floor

now = datetime.now()

year = now.year
month = now.month
day = now.day

hour = now.hour
minute = now.minute
second = now.second
millisecond = floor(datetime.now().microsecond / 1000)
microsecond = now.microsecond

date = now.strftime("%Y-%m-%d")

time24Hour = now.strftime("%H:%M:%S")
time12Hour = now.strftime("%I:%M:%S %p")

I always use this code, which print the year to second in a tuple我总是使用这个代码,它在元组中打印年份到第二个

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

Please try the below lines in order to get the current date.请尝试以下几行以获得当前日期。

import datetime

now = datetime.datetime.now()

print (now.strftime("%Y-%m-%d %H:%M:%S"))

Output:
2020-02-26 21:15:32

Refer : https://beginnersbug.com/how-to-get-the-current-date-in-pyspark-with-example/参考: https : //beginnersbug.com/how-to-get-the-current-date-in-pyspark-with-example/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM