0

I have two date-time string like "1637279999" that converts into "Thursday, 18 November 2021 23:59:59" and "1637193600" that converts into "Thursday, 18 November 2021 00:00:00". I converted using https://www.epochconverter.com/.

Is there any python function that converts directly current date-time (with HH:MM:SS) into the following formats?

String 1: Thursday, 18 November 2021 23:59:59 => 1637279999

String 2: Thursday, 18 November 2021 00:00:00 => 1637193600

Mayur Koshti
  • 1,794
  • 15
  • 20
  • Note: `time.time()` function gives current date time. – Mayur Koshti Nov 18 '21 at 11:38
  • Use `strptime` to parse to datetime, set tzinfo (if certain time zone instead of local time), then use `.timestamp` method. Just have a look at the datetime module docs :) – FObersteiner Nov 18 '21 at 11:40
  • @MrFuppes I am not getting "23:59:59" just works for "00:00:00". Is there any direct function for this ? – Mayur Koshti Nov 18 '21 at 11:46
  • Does this answer your question? [Convert string date to timestamp in Python](https://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python) – FObersteiner Nov 18 '21 at 12:18

1 Answers1

2

Parse the date, add TimeZone info to that, then get the timestamp from it.

from datetime import datetime, timezone


def to_timestamp(date_str):
    date_obj = datetime.strptime(date_str, '%A, %d %B %Y %H:%M:%S')
    date_obj = date_obj.replace(tzinfo=timezone.utc)  # replace your desired TZ here
    return date_obj.timestamp()

rdas
  • 20,604
  • 6
  • 33
  • 46