Pythonを使用してリストのタイムスタンプを編集しますか?関数を使用してPOSIXを読み取り可能な形式に変換します

デビッドビールス

2番目の編集:

タイムゾーンを調整し、フォーマットを変換するための完成したスニペット。このソリューションにつながる詳細については、以下の正解を参照してください。

tzvar = int(input("Enter the number of hours you'd like to add to the timestamp:"))
tzvarsecs = (tzvar*3600)
print (tzvarsecs)

def timestamp_to_str(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%H:%M:%S %m/%d/%Y')

timestamps = soup('span', {'class': '_timestamp js-short-timestamp '})
dtinfo = [timestamp["data-time"] for timestamp in timestamps]
times = map(int, dtinfo)
adjtimes = [x+tzvarsecs for x in times]
adjtimesfloat = [float(i) for i in adjtimes]
dtinfofloat = [float(i) for i in dtinfo]
finishedtimes = [x for x in map(timestamp_to_str, adjtimesfloat)]
originaltimes = [x for x in map(timestamp_to_str, dtinfofloat)]

2回目の編集を終了


編集:

このコードを使用すると、HTMLファイルからPOSIX時間を取得し、ユーザーが入力した時間数を元の値に追加できます。負の数は、時間を差し引くためにも機能します。変更は特にタイムゾーンを調整するためのものであるため、ユーザーは1時間で作業します。

tzvar = int(input("Enter the number of hours you'd like to add to the timestamp:"))
tzvarsecs = (tzvar*3600)
print (tzvarsecs)

timestamps = soup('span', {'class': '_timestamp js-short-timestamp '})
dtinfo = [timestamp["data-time"] for timestamp in timestamps]
times = map(int, dtinfo)
adjtimes = [x+tzvarsecs for x in times]

残っているのは、以下に提案するような機能の逆です。関数を使用して、リスト内の各POSIX時間を読み取り可能な形式に変換するにはどうすればよいですか?

編集終了



以下のコードは、保存されたTwitterHTMLファイルからスクレイピングされたデータを含むcsvファイルを作成します。

Twitterは、すべてのタイムスタンプをブラウザーでユーザーの現地時間に変換します。ツイートのデータがツイーターの現地時間を反映するように、ユーザーがタイムスタンプを特定の時間数だけ調整するための入力オプションが欲しいのですが。

私は現在'title'、各パーマリンクの一部であるという要素をスクレイピングしています代わりに、各ツイートからPOSIX時間を簡単に取得できます。

title="2:29 PM - 28 Sep 2015"

vs

data-time="1443475777" data-time-ms="1443475777000"

次の部分を編集して、ユーザーが入力した変数を各タイムスタンプに追加するにはどうすればよいですか?入力をリクエストするのに助けは必要ありません。入力がPythonに渡された後、タイムスタンプのリストにそれを適用する方法を知っている必要があります。

timestamps = soup('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'})
datetime = [timestamp["title"] for timestamp in timestamps]

このコード/プロジェクトに関連するその他の質問。

BeautifulSoup4のループでエンコードエラーを修正しましたか?

PythonとBeautifulSoup 4でTwitterをスクレイピングしながら、特定の結果に焦点を合わせますか?

Pythonを使用してTwitterでネストされたDivとスパンをスクレイプしますか?


完全なコード。

from bs4 import BeautifulSoup
import requests
import sys
import csv
import re
from datetime import datetime
from pytz import timezone

url = input("Enter the name of the file to be scraped:")
with open(url, encoding="utf-8") as infile:
    soup = BeautifulSoup(infile, "html.parser")

#url = 'https://twitter.com/search?q=%23bangkokbombing%20since%3A2015-08-10%20until%3A2015-09-30&src=typd&lang=en'
#headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
#r = requests.get(url, headers=headers)
#data = r.text.encode('utf-8')
#soup = BeautifulSoup(data, "html.parser")

names = soup('strong', {'class': 'fullname js-action-profile-name show-popup-with-id'})
usernames = [name.contents for name in names]

handles = soup('span', {'class': 'username js-action-profile-name'})
userhandles = [handle.contents[1].contents[0] for handle in handles]  
athandles = [('@')+abhandle for abhandle in userhandles]

links = soup('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'})
urls = [link["href"] for link in links]
fullurls = [permalink for permalink in urls]

timestamps = soup('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'})
datetime = [timestamp["title"] for timestamp in timestamps]

messagetexts = soup('p', {'class': 'TweetTextSize  js-tweet-text tweet-text'}) 
messages = [messagetext for messagetext in messagetexts]  

retweets = soup('button', {'class': 'ProfileTweet-actionButtonUndo js-actionButton js-actionRetweet'})
retweetcounts = [retweet.contents[3].contents[1].contents[1].string for retweet in retweets]

favorites = soup('button', {'class': 'ProfileTweet-actionButtonUndo u-linkClean js-actionButton js-actionFavorite'})
favcounts = [favorite.contents[3].contents[1].contents[1].string for favorite in favorites]

images = soup('div', {'class': 'content'})
imagelinks = [src.contents[5].img if len(src.contents) > 5 else "No image" for src in images]

#print (usernames, "\n", "\n", athandles, "\n", "\n", fullurls, "\n", "\n", datetime, "\n", "\n",retweetcounts, "\n", "\n", favcounts, "\n", "\n", messages, "\n", "\n", imagelinks)

rows = zip(usernames,athandles,fullurls,datetime,retweetcounts,favcounts,messages,imagelinks)

rownew = list(rows)

#print (rownew)

newfile = input("Enter a filename for the table:") + ".csv"

with open(newfile, 'w', encoding='utf-8') as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(['Usernames', 'Handles', 'Urls', 'Timestamp', 'Retweets', 'Favorites', 'Message', 'Image Link'])
    for row in rownew:
        writer.writerow(row)
マウロバラルディ

コードを例として使用すると、vardatetimeは文字列の日付のリストを格納します。それでは、理解のために、プロセスを3つのステップで分析してみましょう。

>>> datetime = [timestamp["title"] for timestamp in timestamps]
>>> print(datetime)
['2:13 AM - 29 Sep 2015', '2:29 PM - 28 Sep 2015', '8:04 AM - 28 Sep 2015']

最初のステップ: Pythonの日時オブジェクトに変換します

>>> datetime_obj = datetime.strptime('2:13 AM - 29 Sep 2015', '%H:%M %p - %d %b %Y')
>>> print(datetime_obj)
datetime.datetime(2015, 9, 29, 2, 13)

2番目のステップ: datetimeオブジェクトをPython構造化時間オブジェクトに変換します

>>> to_time = struct_date.timetuple()
>>> print(to_time)
time.struct_time(tm_year=2015, tm_mon=9, tm_mday=29, tm_hour=2, tm_min=13, tm_sec=0, tm_wday=1, tm_yday=272, tm_isdst=-1)

3番目のステップ:構造化された時間オブジェクトをtime使用に変換しますtime.mktime

>>> timestamp = time.mktime(to_time)
>>> print(timestamp)
1443503580.0

すべて一緒になりました。

import time
from datetime import datetime

...
def str_to_ts(str_date):
    return time.mktime(datetime.strptime(str_date, '%H:%M %p - %d %b %Y').timetuple())

datetimes = [timestamp["title"] for timestamp in timestamps]
times = [i for i in map(str_to_ts, datetimes)]

PS:日時は変数名には不適切な選択です。特にこの文脈で。:-)

更新

リストの各値に関数を適用するには:

def add_time(timestamp, hours=0, minutes=0, seconds=0):
    return timestamp + seconds + (minutes * 60) + (hours * 60 * 60)

datetimes = [timestamp["title"] for timestamp in timestamps]
times = [add_time(i, 5, 0, 0) for i in datetimes]

アップデート2

タイムスタンプを文字列形式の日付に変換するには:

def timestamp_to_str(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%H:%M:%S %m/%d/%Y')

例:

>>> from time import time
>>> from datetime import datetime

>>> timestamp_to_str(time())
'17:01:47 08/29/2016'

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ