Converting a UTC Time to Epoch format - python

I'm trying to convert a specific UTC time & date to seconds since the Epoch; however, I have not been able to figure out how to do this since I am not in the UTC time zone.
I tried using the datetime module to convert a date & time to seconds since the epoch, but python has been using my system's local time so the returned value is off by 7 hours. I understand that I could simply subtract 7*60 so that it would work in my time zone; however, I need this to work in multiple time zones without hardcoding the time change into my program.
This works except it uses the system time (MST), but I am looking for a solution that is specifically UTC time. Note the variables defined here represent an example of a time in UTC that I am trying to convert to seconds since the epoch.
import datetime
year=2019
month=5
day=9
hour=21
minute=45
Time=datetime.datetime(year, month, day, hour, minute).timestamp()
print(Time)
Output:
1557463500.0
Desired output (7 hours earlier):
1557438300.0

import datetime
year=2019
month=5
day=9
hour=21
minute=45
e = datetime.datetime(1970, 1, 1, 0, 0)
t = datetime.datetime(year, month, day, hour, minute)
print((t-e).total_seconds())

You can caclulate the timestamp of epoch date using datetime.datetime.utcfromtimestamp(0).timestamp() and then subtract your current timestamp from it
import datetime
year=2019
month=5
day=9
hour=21
minute=45
#Date timestamp
dt_timestamp=datetime.datetime(year, month, day, hour, minute).timestamp()
#Epoch timestamp
epoch = datetime.datetime.utcfromtimestamp(0).timestamp()
#Epoch
print(dt_timestamp-epoch)
The output will be
1557438300.0

Related

datetime.timestamp not the same as seconds since 1970

I think I'm misunderstanding something regarding datetime timestamps.
The descriptions I've read seem to say that a timestamp represents the Unix time (the number of seconds since 1970)
But when I run the following
import datetime
date = datetime.datetime(2020, 1 , 1, 0, 0, 0)
time1 = datetime.datetime.timestamp(date)
time2 = (date - datetime.datetime(1970,1,1,0,0,0)).total_seconds()
print(time1)
print(time2)
It prints:
1577862000.0
1577836800.0
Shouldn't these be the same? What am I misunderstanding?
Timezones. The unix epoch is Jan 1st 1970 in UTC, but your local zone is not UTC, so when you create a "naive" datetime instance using datetime.datetime(1970,1,1,0,0,0) it's offset from the real unix epoch by several hours.
Attach tzinfo=datetime.timezone.utc to both of the created datetime instances, and you'll see equality.
Alternatively, use datetime.datetime.fromtimestamp(0) instead of datetime.datetime(1970,1,1,0,0,0) to get a "naive" datetime instance coincident with the epoch.

Add year/month/day to an UNIX timestamp with just hour/min/sec in python

The range of my timestamp is from 34200 to 57600, so it covers a part of one day from 9:30 AM). I want to add a specific year/month/day to this timestamp. How can I do that in python? Suppose that my timestamp is 34201.054427731004. I want a timestamp with information about year/month/day (for example, 3/2/2017) as the output. So here, the UNIX output is a full timestamp not just the hour/mean/sec.
Make a datetime object with the date, which will initialise hours and minutes to 0, and add a timedelta with the seconds to it:
from datetime import datetime, timedelta
date = datetime(2017, 2, 3) + timedelta(seconds=34201)
print(date.timestamp())

Python time and date function - confused

I want to take a time stamp from the epoch - 1507498737.999 and store it as float in a nosql database. I also want to convert the epoch time to:
Year
Month
Day
Hour
Minute
Seconds
Milliseconds
DayName
MonthName
others?
I keep running into issues with conversions. My thought is:
Get the now() timestamp (floating)
Convert the timestamp to Year, Month, Day, etc...
How?
If you create a python datetime object, you may access the properties you need.
>>> import datetime
>>> dt = datetime.datetime.fromtimestamp(1507498737.999)
>>> print(dt)
2017-10-09 08:38:57.999000
>>> dt.microsecond
999000
>>> dt.day
9

Python - How to convert datetime data using toordinal considering the time

Let's assume that I have the following data:
25/01/2000 05:50
When I convert it using datetime.toordinal, it returns this value:
730144
That's nice, but this value just considers the date itself. I also want it to consider the hour and minutes (05:50). How can I do it using datetime?
EDIT:
I want to convert a whole Pandas Series.
An ordinal date is by definition only considering the year and day of year, i.e. its resolution is 1 day.
You can get the microseconds / milliseconds (depending on your platform) from epoch using
datetime.datetime.strptime('25/01/2000 05:50', '%d/%m/%Y %H:%M').timestamp()
for a pandas series you can do
s = pd.Series(['25/01/2000 05:50', '25/01/2000 05:50', '25/01/2000 05:50'])
s = pd.to_datetime(s) # make sure you're dealing with datetime instances
s.apply(lambda v: v.timestamp())
If you use python 3.x. You can get date with time in seconds from 1/1/1970 00:00
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()

Calculate time after X hours?

For example, if the start time is 8:00am how do I calculate the time after 20 hours have passed?
Need to use something like timedelta
from datetime import datetime, timedelta
twenty_hours= datetime.now() + timedelta(hours=20)
ofcourse you'll change datetime.now() to your 8am or what ever time you wish
>>> format(twenty_hours, '%H:%M:%S')
'23:24:31'
There are at least two possible interpretations of your question:
Find the local time that is exactly 20 hours from now:
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc) # current time in UTC
in20hours = (now + timedelta(hours=20)).astimezone() # local time in 20 hours
print("Local time in 20 hours: {in20hours:%I:%M %p}".format(**vars())) # AM/PM
Find the time while ignoring any changes in the local UTC offset (due to DST transitions or any other reason):
#!/usr/bin/env python
from datetime import datetime, timedelta, timezone
now = datetime.now() # local time
by20hours = now + timedelta(hours=20) # move clock by 20 hours
print("Move clock by 20 hours: {by20hours:%I:%M %p}".format(**vars())) # AM/PM
Related: python time + timedelta equivalent
Both methods produce the same result if the local utc offset won't change during the next 20 hours. Otherwise the second method fails, to find the time after 20 hours have passed.
You might need the second method if you want to do something at the same local time no matter how many hours have passed in between e.g., if you want to get up at 6am no matter whether 24 hours have passed or not. See How can I subtract a day from a Python date?
More details on the time arithmetics if you are working with local time see at Find if 24 hrs have passed between datetimes - Python.

Categories

Resources