Python time strftime () 函数用于格式化时间,返回以可读字符串表示的当地时间,格式由参数 format 决定。
Python time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import time
#获取当前年月日(单个)
toyear = time.strftime('%Y',time.localtime(time.time())) #"%Y"将被无世纪的年份锁代替
tomon = time.strftime('%m',time.localtime(time.time()))
today = time.strftime('%d',time.localtime(time.time()))
toyear = int(toyear)
tomon = int(tomon)
today = int(today)
#将年月日连接起来,使其成为完整的时间(例:2022 - 03 -27)
todaynow = time.strftime("%Y-%m-%d",time.localtime())
todaynow_mon_day = time.strftime("%m-%d",time.localtime())
print("今天是: " + todaynow_mon_day)
#获取年
def insert_year():
#润年2月29天,平年28天
flag = True
while flag:
input_year = input("输入出生年份:")
input_year = int(input_year)
#今年之前出生的
if input_year <= toyear:
return input_year
flag = False
else:
print("请不要输入未来的年份")
continue
#获取月
def insert_mon():
flag = True
while flag:
input_mon = input("请输入月份:")
input_mon = int(input_mon)
if input_mon > 12 or input_mon < 1:
print("请输入正确的月份")
continue
else:
return input_mon
flag = False
#获取日
def insert_day():
flag = True
while flag:
input_day = input("请输入天数:")
input_day = int(input_day)
if input_day > today:
if input_day > 31 or input_day < 1:
print("请输入正确的天数")
continue
elif input_day == today:
print("生日快乐")
flag = False
return input_day
else:
return input_day
flag = False
else:
return input_day
flag = False
#计算还有多少天生日(生日\今天\生日月\生日天)
def how_long(todaynow, mon, day):
try:
#明年的今天
next_year = int(toyear) + 1
str3 = str(next_year) + "-" + str(mon) + "-" + str(day)
str4 = str(int(toyear)) + "-" + str(mon) + "-" + str(day)
date2 = datetime.datetime.strptime(todaynow[0:10], "%Y-%m-%d") #今天
date3 = datetime.datetime.strptime(str3[0:10], "%Y-%m-%d") #明年生日=今年年份+1 +生日的月日
date4 = datetime.datetime.strptime(str4[0:10], "%Y-%m-%d") #今年的年+生日的月日
num = 0
#明年
#今天过生日:月日相等
if mon == tomon:
if day == today:
print("今天过生日,祝你生日快乐")
num = 0
if day > today:
print("这个月过生日")
num = (date4 - date2).days
if day < today:
print("生日这个月已过")
num = (date3 - date2).days
#已经过了的生日:明年生日-今天
elif mon < tomon:
print("今年生日已经过了")
num = (date3 - date2).days
#还没过生日:今年的年+生日的月日 - 今天的年月日
else:
print("今年的生日还没到")
num = (date4 - date2).days #返回的全部是非0的整数
except ValueError as e:
print("请输入正确的日期,一个月只有适合的天数 " + e)
print("程序结束...")
return num
if __name__ == "__main__":
year = insert_year()
mon = insert_mon()
day = insert_day()
num = how_long(todaynow, mon, day)
if num != 0:
print("距离生日还有" + str(num) + "天")
mybirthday = str(year) + "-" + str(mon) + "-" + str(day)
print("你的生日是: " + mybirthday)
print("输入任意按键退出~")
input()
python中时间日期格式化符号:
- %y 两位数的年份表示(00-99)
- %Y 四位数的年份表示(000-9999)
- %m 月份(01-12)
- %d 月内中的一天(0-31)
- %H 24小时制小时数(0-23)
- %I 12小时制小时数(01-12)
- %M 分钟数(00=59)
- %S 秒(00-59)
- %a 本地简化星期名称
- %A 本地完整星期名称
- %b 本地简化的月份名称
- %B 本地完整的月份名称
- %c 本地相应的日期表示和时间表示
- %j 年内的一天(001-366)
- %p 本地A.M.或P.M.的等价符
- %U 一年中的星期数(00-53)星期天为星期的开始
- %w 星期(0-6),星期天为星期的开始
- %W 一年中的星期数(00-53)星期一为星期的开始
- %x 本地相应的日期表示
- %X 本地相应的时间表示
- %Z 当前时区的名称
- %% %号本身