Process time and date use 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?
https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date
convert string having timezone into to utc datetime object python
https://stackoverflow.com/questions/50679349/convert-string-having-timezone-into-to-utc-datetime-object-python
TypeError: can't compare offset-naive and offset-aware datetimes
https://stackoverflow.com/questions/15307623/cant-compare-naive-and-aware-datetime-now-challenge-datetime-end
 
- reference:
http://www.wklken.me/posts/2015/03/03/python-base-datetime.html
http://blog.sina.com.cn/s/blog_b09d460201018o0v.html

 

posted on 2019-02-11 20:35  冰山上的博客  阅读(964)  评论(0编辑  收藏  举报