1
0

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 2 ็‰ˆ)

1
Posted at

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

ใใ†ใ„ใˆใฐใ€ไฝ•ใฎใŸใ‚ใซๆ›ธใ„ใŸใฎใ‹ๆ€ใ„ๅ‡บใ›ใชใ„ใ‘ใฉใ€ๆ˜”ๆ›ธใ„ใŸใชใ‚ใจๆ€ใ„ๅ‡บใ—ใŸใฎใง.
ๅ˜็ด”ใช UDP ใƒ‘ใ‚ฑใƒƒใƒˆใŒ้ฃ›ใ‚“ใงใ„ใ‚‹ใ ใ‘ใชใ‚“ใงใ™ใ‚ˆใญ.
ใพใ‚ใ€ใใ‚Œใ‚’ๅŸบใซ้ซ˜ๅบฆใช่จˆ็ฎ—ใ‚’ใ—ใฆใ„ใ‚‹ใฏใšใชใ‚“ใงใ™ใŒ...

ใ“ใ‚Œใ€Python 2 ใงใ—ใ‹ๅ‹•ใ‹ใชใ„ใ‹ใ‚‰ Python 3 ใซ็งปๆคใ—ใ‚ˆใ†(็ฌ‘).

ใƒ†ใ‚นใƒˆ

>>> ntp_now('ntp.jst.mfeed.ad.jp')
datetime.datetime(2019, 4, 28, 21, 18, 22)

ใ‚ณใƒผใƒ‰

def ntp_now(server, port = 123):
    from socket import socket, AF_INET, SOCK_DGRAM
    from struct import unpack
    from datetime import datetime
    s = socket(AF_INET, SOCK_DGRAM)
    try:
        s.sendto('\x1b' + 47 * '\0', (server, port))
        result = s.recvfrom(1024)[0]
    finally:
        s.close()
    if result:
        return datetime.fromtimestamp(unpack('!12I', result)[10] - 2208988800L)
    else:
        None
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?