Python 3.2输入日期功能 [英] Python 3.2 input date function

查看:173
本文介绍了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天,并打印2013年1月30日。

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天全站免登陆