A simple Python script to get the date and time in Unix Epoch and in local time

First Published: .

The Unix Epoch is the time, in seconds, that has passed since 1970-01-01 00:00:00 UTC.

#!/usr/bin/env python3

#
# Date time methods
#
# Author: Carles Mateo
# Creation Date: 2019-11-20 17:23 IST
# Description: Class to return Date, datetime, Unix EPOCH timestamp
#

import datetime
import time


class DateTimeUtils:

    def get_unix_epoch(self):
        """
        Will return the EPOCH Time. For convenience is returned as String
        :return:
        """
        s_now_epoch = str(int(time.time()))

        return s_now_epoch

    def get_datetime(self, b_milliseconds=False):
        """
        Return the datetime with miliseconds in format YYYY-MM-DD HH:MM:SS.xxxxx
        or without milliseconds as YYYY-MM-DD HH:MM:SS"""
        if b_milliseconds is True:
            s_now = str(datetime.datetime.now())
        else:
            s_now = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        return s_now


def main():
    o_datetime = DateTimeUtils()
    s_now_epoch = o_datetime.get_unix_epoch()
    s_now_date = o_datetime.get_datetime()

    print(s_now_epoch)
    print(s_now_date)


main()

You can also get the code from:

https://gitlab.com/carles.mateo/blog.carlesmateo.com-source-code/

Views: 1,843 views

Rules for writing a Comment


  1. Comments are moderated
  2. I don't publish Spam
  3. Comments with a fake email are not published
  4. Disrespectful comments are not published, even if they have a valid point
  5. Please try to read all the article before asking, as in many cases questions are already responded

Leave a Reply