Python 3.2 输入日期函数 [英] Python 3.2 input date function

查看:23
本文介绍了Python 3.2 输入日期函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,该函数接受用户输入的日期,将其存储在搁置函数中,并在调用时打印三十天后的日期.

I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.

我试图从一些简单的事情开始:

I'm trying to start with something simple like:

import datetime

def getdate():
    date1 = input(datetime.date)
    return date1

getdate()

print(date1)

这显然行不通.

我已经使用了上述问题的答案,现在我的程序的那部分正在运行!谢谢!现在进入下一部分:

I've used the answers to the above question and now have that section of my program working! Thanks! Now for the next part:

我正在尝试编写一个简单的程序,按照您指示我的方式获取日期并添加 30 天.

I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.

import datetime
from datetime import timedelta

d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)

这给了我一个错误:年、月、日 = map(int, d.split('-'))AttributeError: 'datetime.date' 对象没有属性 'split'

This gives me an error: year, month, day = map(int, d.split('-')) AttributeError: 'datetime.date' object has no attribute 'split'

最终我想要的是 01/01/2013 + 30 天并打印 01/30/2013.

Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.

提前致谢!

推荐答案

input() 方法可以从终端获取文本.因此,您必须想办法解析该文本并将其转换为日期.

The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.

您可以通过两种不同的方式进行处理:

You could go about that in two different ways:

  • 要求用户分别输入日期的3个部分,所以调用input()三次,将结果转化为整数,构建一个日期:

  • Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:

year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)

  • 要求用户以特定格式输入日期,然后将该格式转换为年、月和日的三个数字:

  • Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:

    date_entry = input('Enter a date in YYYY-MM-DD format')
    year, month, day = map(int, date_entry.split('-'))
    date1 = datetime.date(year, month, day)
    

  • 这两种方法都是示例;例如,没有包含错误处理,您需要阅读 Python 异常处理来自己弄清楚.:-)

    Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)

    这篇关于Python 3.2 输入日期函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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