Python中常用的时间和日期函数整理
Python中有许多内置的时间和日期模块可以用来处理时间和日期的操作。下面是一些常用的时间和日期函数的整理。
1. time模块
time模块提供了获取当前时间、睡眠等功能。
- time():获取当前时间的秒数。
- sleep(seconds):让程序暂停指定的秒数。
2. datetime模块
datetime模块提供了日期和时间的处理功能。
- datetime.now():获取当前的日期和时间。
- datetime(year, month, day, hour, minute, second):创建一个指定日期和时间的datetime对象。
- timedelta(days, seconds, microseconds):表示一个时间间隔,可以对日期和时间进行加减操作。
3. calendar模块
calendar模块提供了一些处理日历的功能。
- calendar.month(year, month):返回一个月的日历字符串。
- calendar.weekday(year, month, day):返回一个日期对应的星期几,0表示星期一,1表示星期二,以此类推。
4. strftime和strptime函数
strftime函数可以将datetime对象格式化为指定的字符串,strptime函数可以将字符串解析为datetime对象。
- datetime.strftime(format):将datetime对象格式化为指定的字符串。
- datetime.strptime(date_string, format):将字符串解析为datetime对象。
5. timeit模块
timeit模块提供了一种简单的方式来衡量代码片段的执行时间。
- timeit.timeit(stmt, setup, timer, number):返回代码片段的执行时间。
6. relativedelta函数
relativedelta函数允许我们在datetime对象上执行复杂的日期运算。
- relativedelta(years, months, days, hours, minutes, seconds):在datetime对象上执行日期运算。
7. pytz模块
pytz模块提供了对时区的支持。
- timezone(name):创建一个指定的时区对象。
- localize(dt, tzinfo):将datetime对象与一个时区关联。
- normalize(dt, tzinfo):去除datetime对象的时区信息。
8. arrow模块
arrow模块是一个更加方便和人性化的日期和时间库,使用起来比datetime模块更加简洁。
- arrow.now():获取当前的日期和时间。
- arrow.get(date_string, format):将字符串解析为Arrow对象。
以上是Python中常用的时间和日期函数的整理,通过使用这些函数,可以方便地对时间和日期进行处理和操作。
