3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python ใง ntp server ใ‹ใ‚‰ๆ™‚ๅˆปใ‚’ๅ–ๅพ—ใ™ใ‚‹ (Python 3 ็‰ˆ)

3
Last updated at Posted at 2019-04-28

Python ใง ntp server ใ‹ใ‚‰ๆ™‚ๅˆปใ‚’ๅ–ๅพ—ใ™ใ‚‹ (Python 3 ็‰ˆ)

Python ใง ntp server ใ‹ใ‚‰ๆ™‚ๅˆปใ‚’ๅ–ๅพ—ใ™ใ‚‹ (Python 2 ็‰ˆ) ใ‚’ Python 3 ใซ็งปๆคใ—ใŸ.
2to3 ใ‚’ไฝฟใฃใฆใฟใŸใ‚‰ใ€2208988800L ใฎๆœ€ๅพŒใฎ L ใ‚’ๅ–ใ‚Œใฃใฆ่จ€ใ‚ใ‚ŒใŸใฎใงใ€ใใ‚Œใ‚’ไฟฎๆญฃใ—ใฆๅฎŸ่กŒใ—ใฆใฟใŸใ‚‰

TypeError: a bytes-like object is required, not 'str'

ใฃใฆๆ€’ใ‚‰ใ‚ŒใŸ. ใ—ใ‚‡ใ‚“ใผใ‚Š.

ใƒ†ใ‚นใƒˆ

>>> ntp_now('ntp.jst.mfeed.ad.jp')
datetime.datetime(2019, 4, 29, 0, 3, 30)

ใ‚ณใƒผใƒ‰

def ntp_now(server, port = 123):
    from socket import socket, AF_INET, SOCK_DGRAM
    from struct import unpack
    from datetime import datetime
    with socket(AF_INET, SOCK_DGRAM) as s:
        s.sendto(b'\x1b' + 47 * b'\0', (server, port))
        result = s.recvfrom(1024)[0]
    if result:
        return datetime.fromtimestamp(unpack(b'!12I', result)[10] - 2208988800)
    else:
        None

b ใ‚’ไป˜ใ‘ใพใใฃใฆใ€finally close ใ‚’ with ๆ–‡ใงๅทฎใ—ๆ›ฟใˆใŸ. with ใŒใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใงไฝฟใˆใ‚‹ใฎใฏ 2.6 ใ‹ใ‚‰ใ ใ‹ใ‚‰ 2.5 ๆ™‚ไปฃใซๆ›ธใ„ใŸใฎใ‹ใชใ‚.

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?