Programming‎ > ‎Python‎ > ‎

12-Datetime



from datetime import datetime
import calendar
# utc to unixtimestamp


utc = datetime.utcnow()
print(str(utc))
unixTimestampEpoch = calendar.timegm(utc.utctimetuple())
print(str(unixTimestampEpoch))
                        
# unixtimestamp to utc
utc_new = datetime.utcfromtimestamp(unixTimestampEpoch)
print(str(utc_new))

unixTimestampEpoch = calendar.timegm(utc_new.utctimetuple())
print(str(unixTimestampEpoch))


from datetime import datetime,timedelta
import time

current_time = str(datetime.utcnow()).replace(' ','T')

time.sleep(1)

current_time = current_time.replace('T',' ')
format = "%Y-%m-%d %H:%M:%S.%f"
current_time = datetime.strptime(current_time, format)

new_time = datetime.utcnow() + timedelta(seconds=10)

diff = (new_time - current_time) / timedelta(seconds=1)
print("Duration: %.0f seconds" % diff)
print(str(int(diff)))

if current_time < new_time:
  print("less")
else:
  print("more")



import datetime as dt
import time as tm

time returns the current time in seconds since the Epoch. (January 1st, 1970)

tm.time()
1511435382.15

Convert the timestamp to datetime.

dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
datetime.datetime(2017, 11, 23, 11, 10, 3, 160514)

Handy datetime attributes:

dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime
(2017, 11, 23, 11, 10, 3)

timedelta is a duration expressing the difference between two dates.

delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta
datetime.timedelta(100)

date.today returns the current local date.

today = dt.date.today()
today - delta # the date 100 days ago
datetime.date(2017, 8, 15)

today > today-delta # compare dates
True





Comments