python datetime with 6 digit milliseconds - python

How could I print 6 digit milli seconds in below format
>>> import datetime
>>> datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='milliseconds')
'2022-01-10T18:29:10.698000+05:30'
Actual Output:
'2022-01-10T18:29:10.108+05:30'
Expecting Output something like:
'2022-01-10T18:29:10.108000+05:30'

Use timespec=microseconds:
>>> dt = datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
'2022-01-10T14:05:55.742931+01:00'
Update:
If you want 0 for microsecond value, you can do:
now = datetime.datetime.now().astimezone()
now = now.replace(microsecond=now.microsecond // 1000 * 1000)
now = now.isoformat(timespec='microseconds')
print(now)
# Output
'2022-01-10T14:17:08.386000+01:00'

There are only 1000ms in 1 second, do you mean microseconds?
datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')

If you want utc and milliseconds value, you can do
UTC Convertion
import pytz
from datetime import datetime
epoch: datetime = datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

Related

How can I truncate milliseconds to 2 most significant decimals in strftime()

I have a datetime object that is printed with:
from datetime import datetime
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()
print('TS: {}'.format(ts))
# "2020-12-03 02:13:27.823467"
However, I only want the first 2 digits of the milliseconds to be shown, like this: 2020-12-03 02:13:27.82. Using "%.2f" didn't work, and perhaps there's another time function more suitable?
What is the best way to do this without introducing (possibly laggy) regex string manipulations?
What about something like the following?
import datetime
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.{:02d}'.format(round(now.microsecond, -4))[:3]
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86
EDIT
Perhaps a better parametrized solution would be:
import datetime
def largest_digits(value, num_digits=2, max_digits=6):
discard_digits = num_digits - max_digits
base = 10 ** -discard_digits
return f'{round(value, discard_digits) // base:02d}'
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.' + largest_digits(now.microsecond, 2)
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86
Aaahi, the answer was trivial! Use string selection.
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()[:-4]

convert unix timestamp in milliseconds to UTC time & date formatting python3 [duplicate]

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.
How do I do this?
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
In Python 3.3, added new method timestamp:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
time.mktime
datetime.timetuple
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
http://delorean.readthedocs.org/en/latest/quickstart.html
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000
Recommendedations from the Python 2.7 docs for the time module
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
Here's another form of a solution with normalization of your time object:
def to_unix_time(timestamp):
epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
delta = my_time - epoch
return delta.total_seconds() * 1000.0
>>> import datetime
>>> import time
>>> import calendar
>>> #your datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
>>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
>>> tt = datetime.datetime.timetuple(now)
>>> tt
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9, tm_wday=1, tm_yday=78, tm_isdst=-1)
>>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
>>> sec_epoch_utc = calendar.timegm(tt) * 1000
>>> sec_epoch_utc
1363698009
>>> #If your datetime object is in local timeformat you do this way
>>> sec_epoch_loc = time.mktime(tt) * 1000
>>> sec_epoch_loc
1363678209.0
[1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple
[2] http://docs.python.org/2/library/time.html
A bit of pandas code:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
A lot of these answers don't work for python 2 or don't preserve the milliseconds from the datetime. This works for me
def datetime_to_ms_epoch(dt):
microseconds = time.mktime(dt.timetuple()) * 1000000 + dt.microsecond
return int(round(microseconds / float(1000)))
Here is a function I made based on the answer above
def getDateToEpoch(myDateTime):
res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
return res
You can wrap the returned value like this : str(int(res))
To return it without a decimal value to be used as string or just int (without the str)
This other solution for covert datetime to unixtimestampmillis.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}

Convert string to epoch time?

I have a string in this format '2016-06-15T12:52:05.623Z'. I want to calculate the number of seconds of this time since epoch.
How can I do that?
In Python 3:
import dateutil.parser
t = dateutil.parser.parse("2016-06-15T12:52:05.623Z")
print(t.timestamp())
Use time to return the timestamp from datetime:
import datetime
import time
date = datetime.datetime.strptime('2016-06-15T12:52:05.623Z', "%Y-%m-%dT%H:%M:%S.%fZ")
print time.mktime(date.timetuple())
>> 1466005925.0
from datetime import datetime
my_date = '2016-06-15T12:52:05.623Z'
dtformat = '%Y-%m-%dT%H:%M:%S.%fZ'
d = datetime.strptime(my_date, dtformat)
epoch = datetime.utcfromtimestamp(0)
print (d - epoch).total_seconds()
# OUT: 1465995125.62

Working with time values greater than 24 hours

How does one work with time periods greater than 24 hours in python? I looked at the datetime.time object but this seems to be for handling the time of a day, not time in general.
datetime.time has the requirement of 0 <= hour < 24 which makes it useless if you want to record a time of more than 24 hours unless I am missing something?
Say for example I wanted to calculate the total time worked by someone. I know the time they've taken to complete tasks individually. What class should I be using to safely calculate that total time.
My input data would look something like this:
# The times in HH:MM:SS
times = ["16:35:21", "8:23:14"]
total_time = ? # 24:58:35
Unfortunately there is not a builtin way to construct timedeltas from strings (like strptime() for datetime objects) so we have to build a parser:
>>> from datetime import timedelta
>>> import re
>>> def interval(s):
"Converts a string to a timedelta"
d = re.match(r'((?P<days>\d+) days, )?(?P<hours>\d+):'
r'(?P<minutes>\d+):(?P<seconds>\d+)', str(s)).groupdict(0)
return timedelta(**dict(((key, int(value)) for key, value in d.items())))
>>> times = ["16:35:21", "8:23:14"]
>>> print sum([interval(time) for time in times])
1 day, 0:58:35
EDIT: Old wrong answer (where I misread the question):
If you substract datetimes you get a timedelta object:
>>> import datetime as dt
>>> times = ["16:35:21", "8:23:14"]
>>> fmt = '%H:%M:%S'
>>> start = dt.datetime.strptime(times[1], fmt )
>>> end = dt.datetime.strptime(times[0], fmt)
>>> diff = (end - start)
>>> diff.total_seconds()
29527.0
>>> (diff.days, diff.seconds, diff.microseconds)
(0, 29527, 0)
>>> print diff
8:12:07
As I understand, you want a sum of all times and not difference. So you can convert your time to timedelta and then sum it:
>>> from datetime import timedelta
# get hours, minutes and seconds
>>> tm1 = [map(int, x.split(':')) for x in times]
# convert to timedelta
>>> tm2 = [timedelta(hours=x[0], minutes=x[1], seconds=x[2]) for x in tm1]
# sum
>>> print sum(tm2, timedelta())
1 day, 0:58:35

python subtract time and run if loop

I want to compare two times and if the new time is more than 2min then the if statement will print output, I can get the output of datetime.datetime.now() , but how do I check whether the old time is less than 2mins?
#!/usr/bin/env python
import datetime
from time import sleep
now = datetime.datetime.now()
sleep(2)
late = datetime.datetime.now()
constant = 2
diff = late-now
if diff <= constant:
print "True time is less than 2min"
else:
print "Time exceeds 2 mins"
any ideas?
UPDATED:
I am now storing the old date as string in file and then subtract it from current time, the old date is stored in the format
2011-12-16 16:14:50.800856
so when I do
now = "2011-12-16 16:14:50.838638"
sleep(2)
nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
late = datetime.now()
diff = late-nnow
it gives me this error
ValueError: unconverted data remains: .838638
Subtracting two datetime instances returns a timedelta that has a total_seconds method:
contant = 2 * 60
diff = late-now
if diff.total_seconds() <= constant:
This is only an answer to the update since the answer from sje397 was perfect.
Use a format string like this to match the whole time string:
nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f')
The %f matches the microseconds after the dot. This is new since Python 2.6.
You could compare datetime objects by themselves:
from datetime import datetime, timedelta
ts = datetime.strptime("2011-12-16 16:14:50.838638Z", '%Y-%m-%d %H:%M:%S.%fZ')
ts += timedelta(minutes=2) # add 2 minutes
if datetime.utcnow() < ts:
print("time is less")
else:
print("time is more or equal")

Categories