=Start=
搜索关键字:
python check date str
参考链接:
- http://stackoverflow.com/questions/16870663/how-do-i-validate-a-date-string-format-in-python
- http://stackoverflow.com/questions/9987818/in-python-how-to-check-if-a-date-is-valid
- http://stackoverflow.com/questions/18539266/how-to-validate-a-specific-date-and-time-format-using-python
- https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
参考解答:
import datetime def validate_date_str(date_str): try: datetime.datetime.strptime(date_str, '%Y-%m-%d') return True except ValueError: return False """ %m 01, 02, ..., 12 %d 01, 02, ..., 31 """ >>> validate_date_str('2003-12-23') >>> validate_date_str('2003-12-32')
在Python中如何比较日期格式的字符串大小
搜索关键字:
python compare date string
参考链接:
- http://stackoverflow.com/questions/8142364/how-to-compare-two-dates
- http://stackoverflow.com/questions/20365854/comparing-two-date-strings-in-python
- http://stackoverflow.com/questions/31350373/comparing-date-strings-in-python #方法2
参考解答:
方法1.先转换成 datetime 对象之后再比较
方法2.相同格式的日期字符串其实可以直接比较(但需要自己先判断日期字符串的合法性)
=END=
《“用Python验证日期字符串的合法性”》 有 1 条评论
Python的datetime和str互转
https://stackoverflow.com/questions/130618/python-date-comparisons
https://blog.csdn.net/wangkun__/article/details/53436266
`
import datetime
# 一天前的现在
yesterday_dt_obj = datetime.datetime.now() – datetime.timedelta(days = 1)
# 日期字符串 生成 日期对象
input_datetime = ‘2018-05-24 17:53:52’
input_dt_obj = datetime.datetime.strptime(input_datetime, “%Y-%m-%d %H:%M:%S”)
# 日期对象 生成 日期字符串
yesterday_dt_str = yesterday_dt_obj.strftime(“%Y-%m-%d %H:%M:%S”)
if input_dt_obj > yesterday_dt_obj:
print ‘{0} > {1}’.format(input_dt_obj, yesterday_dt_obj)
else:
print ‘{0} < {1}'.format(input_dt_obj, yesterday_dt_obj)
# input_dt_obj = datetime.datetime.strptime(input_datetime, "%F %T")
# ValueError: 'F' is a bad directive in format '%F %T'
`