Comment puis-je convertir un objet datetime Python en heure Unix (secondes/millisecondes depuis l'époque 1970) ?

Patricia Arquette
Libérer: 2024-11-14 18:31:02
original
281 Les gens l'ont consulté

How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 epoch)?

Converting Datetime Objects to Epoch Time (Unix Time) in Python

In Python, converting datetime objects to Unix time, or milliseconds since the 1970 epoch, is a common task. The following question delves into how to accomplish this conversion effectively:

Question:

How can I convert a Python datetime object to unix time, or seconds/milliseconds since the 1970 epoch?

Answer:

One of the most straightforward solutions is to utilize the "unix_time_millis" function, as demonstrated below:

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0
Copier après la connexion

Explanation:

  1. import datetime: This line imports the datetime module, which provides the necessary functionality for handling date and time operations.
  2. epoch = datetime.datetime.utcfromtimestamp(0): This line defines the epoch, which represents the point in time from which Unix time is measured (January 1, 1970 at 00:00:00 UTC).
  3. def unix_time_millis(dt): This defines a function called "unix_time_millis" that takes a datetime object "dt" as its parameter.
  4. (dt - epoch): This calculates the time difference between the input datetime "dt" and the epoch.
  5. .total_seconds(): This converts the time difference from a timedelta object to a float representing the total number of seconds.
  6. * 1000.0: This multiplies the number of seconds by 1000 to convert it to milliseconds.

By using this function, you can effortlessly convert any datetime object to Unix time in milliseconds.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal