由“闰年”判断想到的日期与字符串间的转换

一、时间字符串格式转化:

1、时间格式的字符串转时间

  from time import strptime

  >>> s_time = strptime("2020-01-10 09:29:15", "%Y-%m-%d %H:%M:%S")

  >>> print(s_time)
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=9, tm_min=29, tm_sec=15, tm_wday=4, tm_yday=10, tm_isdst=-1)

  >>> print(s_time.tm_year)

  2020

 

  >>> s_time = strptime("2020-01", "%Y-%m")

  >>> print(s_time)
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=-1)
  >>> print(s_time.tm_year)
  2020

2、时间转字符串

  >>> from time import strptime, strftime, localtime

  >>> print(localtime())
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=9, tm_min=35, tm_sec=42, tm_wday=4, tm_yday=10, tm_isdst=0)
  >>> print(localtime().tm_year, localtime().tm_mday)
  2020 10

  >>> print(type(strftime("%Y-%m-%d %H:%M:%S", localtime())))
  <class 'str'>

  >>> print(strftime("%m-%d-%Y %H:%M:%S", localtime()))
  01-10-2020 09:42:49
  >>> print(type(strftime("%m-%d-%Y %H:%M:%S", localtime())))
  <class 'str'>

二、闰年判断

  import calendar

  from datetime import date

  from time import strptime, strftime, localtime

  calendar中的 isleap可以返回True(闰年)和False(不是闰年)

  >>> print(calendar.isleap(2012))

  True

  >>> print(calendar.isleap(date.today().year))
  True

  >>> print(calendar.isleap(localtime().tm_year))
  True

  ss = "2013"

  >>> print(calendar.isleap(datetime.datetime.strptime(ss, "%Y").year))
  False

posted @ 2020-01-10 09:58  土豆笔记  阅读(243)  评论(0编辑  收藏  举报