Python日期时间函数:必备10个函数
Python提供了很多处理日期和时间的函数和模块,下面列举了10个常用的日期时间函数。
1. datetime.now():返回当前日期和时间的datetime对象。比如datetime.datetime(2021, 10, 30, 19, 30, 0)表示2021年10月30日19时30分0秒。
2. strftime(format):将datetime对象格式化为指定格式的字符串。format参数可以指定日期和时间的各种格式,比如"%Y-%m-%d %H:%M:%S"表示年-月-日 时:分:秒。
3. strptime(date_string, format):将字符串解析为datetime对象。其中date_string是一个表示日期和时间的字符串,format参数指定了解析的格式。
4. timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):创建一个时间差,可以用来对datetime进行加减操作。参数可以指定各个单位的时间间隔。
5. date(year, month, day):创建一个表示日期的date对象。比如date(2021, 10, 30)表示2021年10月30日。
6. time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0):创建一个表示时间的time对象。比如time(19, 30, 0)表示19时30分0秒。
7. datetime.combine(date, time):将一个date对象和一个time对象合并为一个datetime对象。
8. datetime.strptime(date_string, format):和strptime函数类似,但是返回一个datetime对象。
9. datetime.strftime(format):和strftime函数类似,但是作用于datetime对象。
10. datetime.timedelta.total_seconds():返回时间间隔的总秒数。
以上是10个常用的日期时间函数,可以满足大部分的日期时间处理需求。如果需要更复杂的功能,可以使用Python中的calendar、time和dateutil等模块。
