Learn Python with Steem #09 笔记

in #blog7 years ago (edited)

Learn Python with Steem #09 笔记


[toc]

划重点

  • 遍历字典

利用dict.items()方法,用一个循环语句遍历整个字典的所有元素。

  • 转换 Reputation 和 Voting Power 的原始数据

直接获取的某些数据是生的,需要煮(转换)一下才能吃。

  • 解析时间

使用Python的dateutil和datetime模块来解析和处理时间数据。

编程练习

from steem import Steem
from steem.converter import Converter
# import sys
import math
from dateutil import parser
from dateutil.tz import *
from datetime import datetime, timezone, timedelta
from pprint import pprint
class Steemains(Steem):
    def __init__(self, _account_name='yjcps'):
        Steem.__init__(self)
        self.account_name = _account_name
        self.account_info = self.get_account(self.account_name)

    @property
    def view_account_info(self):
        post_count = self.account_info.get('post_count')
        balance = self.account_info.get('balance')
        created = self.parse_date(
            self.account_info.get('created'))
        sbd_balance = self.account_info.get('sbd_balance')
        vesting_shares = self.parse_vests(
            self.account_info.get('vesting_shares'))
        delegated_vesting_shares = self.parse_vests(
            self.account_info.get('delegated_vesting_shares'))

        converter = Converter()
        sp = converter.vests_to_sp(vesting_shares)
        delegated_sp = converter.vests_to_sp(delegated_vesting_shares)

        voting_power = self.parse_voting_power(
            self.account_info.get('voting_power'))
        reputation = self.parse_reputation(
            self.account_info.get('reputation'))
        last_post_date = self.parse_date(
            self.account_info.get('last_root_post'))
        time_since_last_post = datetime.utcnow().replace(
            tzinfo=timezone.utc) - last_post_date
        days_since_last_post = time_since_last_post.days

        #         print(_timedelta)

        return {
            'account_name': self.account_name,
            'balance': balance,
            'created':
            self.utc_2_local_date(created).strftime(
                '%Y-%m-%d-%a %H:%M:%S'),
            'sbd_balance': sbd_balance,
            'vesting_shares': vesting_shares,
            'delegated_vesting_shares': delegated_vesting_shares,
            'sp': sp,
            'delegated_sp': delegated_sp,
            'post_count': post_count,
            'voting_power': voting_power,
            'reputation': reputation,
            'last_post_date':
            self.utc_2_local_date(last_post_date).strftime(
                '%Y-%m-%d-%a %H:%M:%S'),
            'days_since_last_post': days_since_last_post
        }

    def get_post_histry(self):
        pass

    @staticmethod
    def utc_2_local_date(_utcdate):
        _timedelta = datetime.now() - datetime.utcnow()
        return _utcdate.astimezone(timezone(_timedelta))

    @staticmethod
    def parse_vests(_vests):
        return float(_vests.split()[0])

    @staticmethod
    def parse_voting_power(voting_power):
        return int(voting_power) / 100

    @staticmethod
    def parse_reputation(raw_reputation):
        return (math.log10(int(raw_reputation)) - 9) * 9 + 25

    @staticmethod
    def parse_date(_date):
        utc_date = parser.parse(_date).replace(tzinfo=timezone.utc)
        return utc_date
yjcps = Steemains('yjcps')
pprint(yjcps.view_account_info)
{'account_name': 'yjcps',
 'balance': '0.437 STEEM',
 'created': '2018-01-04-Thu 13:25:18',
 'days_since_last_post': 0,
 'delegated_sp': 57.07436926020711,
 'delegated_vesting_shares': 115562.393455,
 'last_post_date': '2018-08-19-Sun 07:01:57',
 'post_count': 261,
 'reputation': 51.49449059489242,
 'sbd_balance': '4.499 SBD',
 'sp': 121.35204133768676,
 'vesting_shares': 245709.808613,
 'voting_power': 68.73}
deanliu = Steemains('deanliu')
pprint(deanliu.view_account_info)
del deanliu
{'account_name': 'deanliu',
 'balance': '105.649 STEEM',
 'created': '2016-07-14-Thu 13:56:39',
 'days_since_last_post': 0,
 'delegated_sp': 3028.3048743103254,
 'delegated_vesting_shares': 6131616.465781,
 'last_post_date': '2018-08-19-Sun 11:23:24',
 'post_count': 9998,
 'reputation': 74.33099682076877,
 'sbd_balance': '189.594 SBD',
 'sp': 17333.498512941853,
 'vesting_shares': 35096322.630247,
 'voting_power': 55.17}
dapeng = Steemains('dapeng')
pprint(dapeng.view_account_info)
del dapeng
{'account_name': 'dapeng',
 'balance': '229.299 STEEM',
 'created': '2016-10-14-Fri 19:03:39',
 'days_since_last_post': 2,
 'delegated_sp': 3909.296719340023,
 'delegated_vesting_shares': 7915420.822822,
 'last_post_date': '2018-08-16-Thu 20:57:21',
 'post_count': 5926,
 'reputation': 67.26589131476406,
 'sbd_balance': '30.081 SBD',
 'sp': 5186.613554620994,
 'vesting_shares': 10501691.705077,
 'voting_power': 69.86}
for key,value in yjcps.view_account_info.items():
    print(key,':',value)
account_name : yjcps
balance : 0.437 STEEM
created : 2018-01-04-Thu 13:25:18
sbd_balance : 4.499 SBD
vesting_shares : 245709.808613
delegated_vesting_shares : 115562.393455
sp : 121.35205839875916
delegated_sp : 57.07437728438151
post_count : 261
voting_power : 68.73
reputation : 51.49449059489242
last_post_date : 2018-08-19-Sun 07:01:57
days_since_last_post : 0
display_message = '''
Username: \t{account_name}
Reputation: \t{reputation}
Created:\t{created}
Last Post: \t{last_post_date} ({days_since_last_post} days ago)
===========================================
STEEM Balance:\t{balance}
SBD Balance:\t{sbd_balance}
SP: \t\t{sp}
Delegated SP:\t{delegated_sp}
Total Posts:\t{post_count}
Voting Power:\t{voting_power}%
'''.format(**yjcps.view_account_info)
print(display_message)
Username:   yjcps
Reputation:     51.49449059489242
Created:    2018-01-04-Thu 13:25:18
Last Post:  2018-08-19-Sun 07:01:57 (0 days ago)
===========================================
STEEM Balance:  0.437 STEEM
SBD Balance:    4.499 SBD
SP:         121.35205862624704
Delegated SP:   57.07437749836572
Total Posts:    261
Voting Power:   68.73%
pprint(yjcps.account_info)
del yjcps

补充

解析日期字符串

python-dateutil

# ISO format
dt = parser.parse("2018-01-04T14:49:21")
print(dt)
print(type(dt))
2018-01-04 14:49:21
<class 'datetime.datetime'>
# 设置时区
TZOFFSETS = {"BRST": -10800}
dt = parser.parse("Thu Sep 25 10:36:28 BRST 2003",  tzinfos=TZOFFSETS)
print(dt)
print(type(dt))
2003-09-25 10:36:28-03:00
<class 'datetime.datetime'>
dt = parser.parse("2003-09-25T10:49:41.5-03:00")
print(dt)
2003-09-25 10:49:41.500000-03:00
dt = parser.parse("20030925T104941")
print(dt)
2003-09-25 10:49:41
dt = parser.parse("2003.Sep.25")
print(dt)
2003-09-25 00:00:00
dt = parser.parse("Tuesday, April 12, 1952 AD 3:30:42pm PST", ignoretz=True)
print(dt)
1952-04-12 15:30:42

时区转换

# 当前本地时间
print(datetime.now())
# 当前UTC时间
print(datetime.utcnow())

print()

# 时差
dt = datetime.now() - datetime.utcnow()
print(dt)

print()

# 设置时区为UTC+0:00
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)

# 设置时区为UTC+8:00
_bj_dt = utc_dt.astimezone(timezone(dt))
print(_bj_dt)

# 设置时区为UTC+5:00
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=5)))
print(bj_dt)


2018-08-19 11:35:33.051849
2018-08-19 03:35:33.051849

8:00:00

2018-08-19 03:35:33.052827+00:00
2018-08-19 11:35:33.052827+08:00
2018-08-19 08:35:33.052827+05:00

时间格式转换

dt = parser.parse("2018-08-18T23:01:57")
print(dt)
2018-08-18 23:01:57
# datetime 2 timestamp
timestamp = dt.timestamp()
print(timestamp)

print()

# timestamp 2 datetime
print(datetime.fromtimestamp(timestamp))
print(datetime.utcfromtimestamp(timestamp))
1534604517.0

2018-08-18 23:01:57
2018-08-18 15:01:57
# datetime 2 string
str_time = dt.strftime('%Y/%m/%d %H:%M:%S')
print(str_time)
print(type(str_time))
2018/08/18 23:01:57
<class 'str'>

[DA series - Learn Python with Steem]

我的笔记:

Sort:  

Hi @yjcps, I'm @checky ! While checking the mentions made in this post I noticed that @staticmethod doesn't exist on Steem. Maybe you made a typo ?

If you found this comment useful, consider upvoting it to help keep this bot running. You can see a list of all available commands by replying with !help.

补充之前的总算看完了,我看了好久,我好晕~~

看完咯,要用的时候再来拿,哈哈哈哈~