Get timestamp for hour of current day

Ok, I need a way to get the timestamp for the current day but at a certain time.

So for example, I want the unix timestamp for today at 7:30PM - what would I do to get that value? In PHP it's possible with the strtotime() but I'm not sure how to do this in Python.

Edit: To clarify, I mean the current day not a statically written day. So if I ran this script tomorrow it would return the timestamp for 7:30PM tomorrow.

Upvotes: 0

Views: 4268

Answers (3)

AMacK
AMacK

Reputation: 1396

from datetime import datetime

now = datetime.utcnow() # Current time
then = datetime(1970,1,1) # 0 epoch time
ts = now - then

ts = ts.days * 24 * 3600 + ts.seconds
# alternatively, per Martijn Pieters
ts = int(ts.total_seconds())

Upvotes: 1

Maciej Gol
Maciej Gol

Reputation: 15854

calendar.timegm method returns a timestamp out of passed time tuple:

import calendar
from datetime import datetime

d = datetime(year=2014, month=7, day=8, hour=7, minute=30)
calendar.timegm(d.utctimetuple())
# 1404804600

datetime.utcfromtimestamp(calendar.timegm(d.utctimetuple()))
# datetime.datetime(2014, 7, 8, 7, 30)

The important things are utctimetuple and utcfromtimestamp. You would certainly want a UTC timestamp, and not one in your local timezone.

import calendar
from datetime import datetime
from pytz import timezone, utc

tz = timezone('Europe/Warsaw')
aware = datetime(year=2014, month=7, day=8, hour=7, minute=30)
aware = tz.localize(aware)
# datetime.datetime(2014, 7, 8, 7, 30, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)

stamp = calendar.timegm(aware.utctimetuple())
# 1404797400

d = datetime.utcfromtimestamp(stamp)
# datetime.datetime(2014, 7, 8, 5, 30)

d = d.replace(tzinfo=utc)
d.astimezone(tz)
# datetime.datetime(2014, 7, 8, 7, 30, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)

Upvotes: 0

Philippe T.
Philippe T.

Reputation: 1192

you can use the time module :

from datetime import datetime   
from time import mktime
# like said Ashoka
ts = datetime.strptime("2014-7-7 7:30","%Y-%m-%d %H:%M")
#you have now your datetime object
print mktime(ts.timetuple())
# print 1404711000.0
print int(mktime(ts.timetuple()))
# print 1404711000

be careful mktime don't care of time zone so if you want to have a UTC time zone and still use time , convert date before:

import pytz
fr = pytz.timezone('Europe/Paris')
#localize
ts = fr.localize(ts)
#timestamp in UTC
mktime(ts.astimezone(pytz.UTC).timetuple())

Upvotes: 0

Related Questions