Removing nanoseconds in a datetime string
I'm using java but didn't want to tag it as java since it's basically just pure regex
It's probably best to approach with java.time
,
but since you insist:
time.replaceFirst( "\\.\\d*(Z)?$", "$1");
How to convert time 24-hour to AM/PM and remove nanoseconds & seconds via time4j?
This is straight forward as long as you know that the dedicated formatter API in Time4J is based on ChronoFormatter:
Locale ukraine = new Locale("en", "UA"); // or use new Locale("en", "001") for worldwide
TZID winZone = WindowsZone.of("FLE Standard Time").resolveSmart(ukraine);
PlainTime currentTime = SystemClock.inZonalView(winZone).now().toTime();
System.out.println(currentTime); // T12:02:40,344
// truncate seconds and nanoseconds
currentTime = currentTime.with(PlainTime.PRECISION, ClockUnit.MINUTES);
System.out.println(currentTime); // T12:02
// format in am/pm-notation
ChronoFormatter<PlainTime> f1 =
ChronoFormatter.ofTimePattern("h:mm a", PatternType.CLDR, Locale.US);
String formatted1 = f1.format(currentTime);
System.out.println(formatted1); // 12:02 pm
// or use styled formatter (which has only limited control over displayed precision)
ChronoFormatter<PlainTime> f2 =
ChronoFormatter.ofTimeStyle(DisplayMode.SHORT, Locale.US);
String formatted2 = f2.format(currentTime);
System.out.println(formatted2); // 12:02 pm
A style-based solution (as demonstrated above for Time4J) is appropriate if you want to let the locale control the format pattern. For example, a german locale would print "12:02" instead of "12:02 pm" (US).
By the way, you are also free to use the format-API of java.time
if you want because PlainTime
implements the JSR-310-interface TemporalAccessor
:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.US);
System.out.println(dtf.format(currentTime)); // 12:02 PM
Here the different capitalization originates from the fact that the JDK (at least on my system) still uses older CLDR-data for internationalization while Time4J has its own resources based on actual CLDR-version v33. A future Java version will surely change the capitalization. In general, I still recommend to use ChronoFormatter
for sake of more features, better i18n and more performance. For example, the reverse way of parsing am/pm-literals is more reliable using Time4J than in java.time
if you work with different locales.
If you like to use "AM" and "PM" in capitalized letters (or any other customized format) together with ChronoFormatter
then you can also use:
Map<Meridiem, String> map = new EnumMap<>(Meridiem.class);
map.put(Meridiem.AM, "AM");
map.put(Meridiem.PM, "PM");
ChronoFormatter<PlainTime> f3 =
ChronoFormatter
.setUp(PlainTime.axis(), Locale.ROOT)
.addPattern("h:mm ", PatternType.CLDR)
.addText(PlainTime.AM_PM_OF_DAY, map)
.build();
String formatted3 = f3.format(currentTime);
System.out.println(formatted3); // 12:02 PM
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
SQL Server remove milliseconds from datetime
You just have to figure out the millisecond part of the date and subtract it out before comparison, like this:
select *
from table
where DATEADD(ms, -DATEPART(ms, date), date) > '2010-07-20 03:21:52'
remove milliseconds from Datetime in TZ format
You could drop the miliseconds part from the string, and then convert:
as.POSIXct(gsub("\\.[0-9]+Z", "", timestamp),
format="%Y-%m-%dT%H:%M:%S", tz="GMT")
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
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)
Related Topics
How to Check All Versions of Python Installed on Osx and Centos
How to Install Pip for a Specific Python Version
Easiest Way to Convert Two Columns to Python Dictionary
How to Concatenate/Append Multiple Spark Dataframes Column Wise in Pyspark
How to Save a Pandas Dataframe Table as a Png
Python: Pandas Pd.Read_Excel Giving Importerror: Install Xlrd >= 0.9.0 for Excel Support
How to Align Labels and Entry Boxes in a Gui Program
How to Remove Zeros After Decimal from String Remove All Zero After Dot
Could Not Translate Host Name "Db" to Address Using Postgres, Docker Compose and Psycopg2
Why I Get Key Error Even Though Column Present in Pandas
How to Call a Django Function on Button Click
How to Extract a Value (I Want an Int Not Row) from a Dataframe and Do Simple Calculations on It
Python - Automatically Adjust Width of an Excel File'S Columns
Most Pythonic Way to Kill a Thread After Some Period of Time
How to Sum Dictionaries Values With Same Key Inside a List