Remove Hours:Seconds:Milliseconds in Datetime Object

Remove hours:seconds:milliseconds in DateTime object

To answer your question, no - you would have to store it in a different type. The most simple choice is to use a string.

string date = dateTime.ToString("MM:dd:yyyy");

However I'd also strongly advise against storing dates internally in your program as strings. This will make it difficult to do any calculations or comparisons on them. Furthermore I'd advise you against forcing a specific culture for your date representation as it means your application probably won't work as expected in other cultures than yours.

A slightly more sophisticated approach is to create a custom class which overrides ToString. I'd also avoid this though, because it will still be difficult to use your type with the standard library functions. You will have to convert back and forth all the time.

Just leave it as a DateTime and do the conversion to string only in the presentation layer. You can use DateTime.ToShortDateStringto print a user friendly culture aware string.

How to format DateTime in Flutter? Remove milliseconds in DateTime?

Try out Jiffy, make it easier to work with date and time

To format your DateTime just pass in your result date, see below

this.date1 = Jiffy(date).format('yyyy-MM-dd'); // 2021-03-24

// or you can also use default formats

this.date1 = Jiffy(date).yMMMMd; // March 24, 2021

simple way to drop milliseconds from python datetime.datetime object

You can use datetime.replace() method -

>>> d = datetime.datetime.today().replace(microsecond=0)
>>> d
datetime.datetime(2015, 7, 18, 9, 50, 20)

python datetime remove minute and second information

You can easily modify just a few fields using datetime.datetime.replace

old_date = datetime.datetime(2011, 3, 23, 16, 45)
new_date = old_date.replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=1)

How to remove milliseconds in datetime python?

To get the time live, you can use this code:

import time
time = str(time.strftime("%M")) + ":" + str(time.strftime("%S"))
print(time)

This will give you the current time in Minutes and Seconds, and if you put it in a loop, it will keep updating itself.

If you want the day and month, you can use

print(time.strftime("%A, %B %e")) - 

With this code, you can then subtract the Xmas date from the current date, and retrieve what you want.

This would be your final code:

import time
month = time.strftime("%m")
day = time.strftime("%d")
hour = time.strftime("%H")
minute = time.strftime("%M")
second = time.strftime("%S")
chrmonth = 12
chrday = 23
chrhour = 12
chrminute = 60
chrsecond = 60
print("The time until christmas is, ", int(chrmonth) - int(month), "months", int(chrday) - int(day), "days", int(chrhour) - int(hour), "hours", int(chrminute) - int(minute), "minutes", int(chrsecond) - int(second), "seconds")

Hopefully this helps!

Removing milliseconds from datetime object in Python

You already have a datetime object, you do not need to parse it again. The datetime.fromtimestamp() call was enough.

Remove the datetime.strptime() line.

created_date = datetime.fromtimestamp(ctime)
created_date = created_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(created_date)

I also changed your strftime() call, it is a method, you just call it on the datetime object you have.

I suspect that you printed the return value of the datetime.fromtimestamp() call, and got confused. The str() conversion of a datetime() instance formats the value as a ISO 8601 string. Note that even if you did have a string, you used the wrong format (there is no timezone in that string, so %Z does not apply).

If you needed a datetime object, rather than a formatted string, you could also just have converted your timestamp to an integer; the microseconds are captured in the decimal portion of the timestamp:

>>> ctime = 1505252035.28109
>>> datetime.fromtimestamp(ctime)
datetime.datetime(2017, 9, 12, 22, 33, 55, 281090)
>>> datetime.fromtimestamp(int(ctime))
datetime.datetime(2017, 9, 12, 22, 33, 55)
>>> print(_)
2017-09-12 22:33:55

How to truncate milliseconds off of a .NET DateTime

The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).

DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);

or the equivalent and shorter:

dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));

This could be generalized into an extension method:

public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}

which is used as follows:

dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...

How to remove seconds from datetime?

Solutions if need datetimes in output:

df = pd.DataFrame({'start_date_time': ["2016-05-19 08:25:23","2016-05-19 16:00:45"]})
df['start_date_time'] = pd.to_datetime(df['start_date_time'])
print (df)
start_date_time
0 2016-05-19 08:25:23
1 2016-05-19 16:00:45

Use Series.dt.floor by minutes T or Min:

df['start_date_time'] = df['start_date_time'].dt.floor('T')

df['start_date_time'] = df['start_date_time'].dt.floor('Min')

You can use convert to numpy values first and then truncate seconds by cast to <M8[m], but this solution remove possible timezones:

df['start_date_time'] = df['start_date_time'].values.astype('<M8[m]')
print (df)
start_date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00

Another solution is create timedelta Series from second and substract:

print (pd.to_timedelta(df['start_date_time'].dt.second, unit='s'))
0 00:00:23
1 00:00:45
Name: start_date_time, dtype: timedelta64[ns]

df['start_date_time'] = df['start_date_time'] -
pd.to_timedelta(df['start_date_time'].dt.second, unit='s')
print (df)
start_date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00

Timings:

df = pd.DataFrame({'start_date_time': ["2016-05-19 08:25:23","2016-05-19 16:00:45"]})
df['start_date_time'] = pd.to_datetime(df['start_date_time'])

#20000 rows
df = pd.concat([df]*10000).reset_index(drop=True)


In [28]: %timeit df['start_date_time'] = df['start_date_time'] - pd.to_timedelta(df['start_date_time'].dt.second, unit='s')
4.05 ms ± 130 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [29]: %timeit df['start_date_time1'] = df['start_date_time'].values.astype('<M8[m]')
1.73 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [30]: %timeit df['start_date_time'] = df['start_date_time'].dt.floor('T')
1.07 ms ± 116 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [31]: %timeit df['start_date_time2'] = df['start_date_time'].apply(lambda t: t.replace(second=0))
183 ms ± 19.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Solutions if need strings repr of datetimes in output

Use Series.dt.strftime:

print(df['start_date_time'].dt.strftime('%Y-%m-%d %H:%M'))
0 2016-05-19 08:25
1 2016-05-19 16:00
Name: start_date_time, dtype: object

And if necessary set :00 to seconds:

print(df['start_date_time'].dt.strftime('%Y-%m-%d %H:%M:00'))
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
Name: start_date_time, dtype: object

Strip seconds from datetime

You can do

DateTime dt = DateTime.Now;
dt = dt.AddSeconds(-dt.Second);

to set the seconds to 0.



Related Topics



Leave a reply



Submit