python处理时间和日期

Posted 冰山上的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python处理时间和日期相关的知识,希望对你有一定的参考价值。

time and date
error correction in graph (Datetime obj->string):dt_obj.strftime(format))
 
import time, datetime
1. datetime obj
1) datetime
datetime.datetime.now()
datetime.datetime.now() - datetime.timedelta(days=42)
datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime(*time.localtime()[0:6])
datetime.datetime.strptime("2016-05-04 00:00:00", "%Y-%m-%d %H:%M:%S")
datetime.datetime.fromtimestamp(1462291200.0)
datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) == datetime.datetime.utcfromtimestamp(time.mktime(time.localtime()))
2) date
datetime.datetime.now().date()
datetime.date.today()
datetime.date.today() + datetime.timedelta(days=42)
3) timedelta
datetime.timedelta(days=42)
# datetime.timedelta(days=42).total_seconds()
(datetime.datetime.now() - datetime.datetime(2016,5,4,0,0,0))
# (datetime.datetime.now() - datetime.datetime(2016,5,4,0,0,0)).total_seconds()
 
2. time tuple
time.localtime()
time.gmtime()
datetime.datetime.now().timetuple()
time.strptime("2016-05-04 00:00:00", "%Y-%m-%d %H:%M:%S")
time.localtime(1462291200.0)
 
3. string
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 
4. time stamp
time.time()
time.mktime(time.localtime())
time.mktime(time.gmtime())
int(time.time()) + 86400 * days
 
- iteration:
import datetime
begin, end = \'20151101\', datetime.datetime.today().strftime("%Y%m%d")
begin_tuple, end_tuple = datetime.datetime.strptime(begin, "%Y%m%d"), datetime.datetime.strptime(end, "%Y%m%d")
 
cur_tuple = begin_tuple
while cur_tuple <= end_tuple:
    cur = cur_tuple.strftime("%Y%m%d")
    print cur
    cur_tuple += datetime.timedelta(days=30)

 

- use dateutil:
import datetime
from dateutil.rrule import rrule, MONTHLY
begin_day = datetime.datetime.strptime("2015-11-01", "%Y-%m-%d")
end_day = (datetime.datetime.today() + datetime.timedelta(days=31))
split_days = rrule(MONTHLY,dtstart=begin_day,until=end_day)
for ld, rd in zip(*[iter(split_days[i:]) for i in range(2)]):
    print ld, rd

 

- parse an ISO 8601-formatted date:
import datetime
import dateutil.parser
import pytz
dt = dateutil.parser.isoparse("2020-05-11T02:00:15.696+0530").astimezone(UTC)
dt2 = datetime.datetime.strptime("2015-11-01", "%Y-%m-%d").replace(tzinfo=pytz.UTC)
How to parse an ISO 8601-formatted date?
convert string having timezone into to utc datetime object python
TypeError: can\'t compare offset-naive and offset-aware datetimes
 
- reference:

 

以上是关于python处理时间和日期的主要内容,如果未能解决你的问题,请参考以下文章

你如何在 python 中处理 graphql 查询和片段?

在 Python 多处理进程中运行较慢的 OpenCV 代码片段

arrow python处理日期时间

python常用代码片段总结

仅需6道题轻松掌握Python时间和日期处理 | Python技能树征题

如何从片段中调用 getSupportFragmentManager()?