在pandas datetime中转换混合日期类型

时间:2019-07-02 09:16:32

标签: python pandas dataframe datetime epoch

我有一个数据框,其中包含混合格式的日期(例如,包含纪元)

@PreAuthorize("hasRole('SUPER_ADMIN')")
@GetMapping(path = "/useTenant/{tenantId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ResponseDTO> useTenant(@PathVariable Long tenantId) {
    HttpStatus status = HttpStatus.OK;
    boolean error = false;
    String message = languageMessageService.getMessage(MultiLanguageKey.SUCCESS);

    // fetch master tenant by id
    Optional<MasterTenant> optional = masterTenantService.findById(tenantId);
    if (optional.isPresent()) {
        CustomUserDetails customUserDetails = customUserDetailsService.getUserDetail();
        //Changing Tenant ID
        customUserDetails.setTenant(optional.get().getTenantId());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            // Update Current user by changing tenant id in SecurityContextHolder
            UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
            auth.setDetails(customUserDetails);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
    } else {
        error = false;
        message = languageMessageService.getMessage(MultiLanguageKey.TENANT_NOT_FOUND);
    }
    return new ResponseEntity<>(new ResponseDTO(error, message), status);
}

,我想转换为日期时间,但是如果我键入

df = pandas.DataFrame(data=[1562054799651,'2019-07-02','2007-10-01 00:00:00'],columns=['date'])

我明白了

pandas.to_datetime(df['date'], errors="coerce")

问题在于,第一个日期是'ms'中的一个时期。...

如果我键入

0   1970-01-01 00:26:02.054799651 <- THIS IS WRONG SINCE IT SHOULD BE 2019-07-02 08:06:39.651
1   2019-07-02 00:00:00.000000000
2   2007-10-01 00:00:00.000000000
Name: date, dtype: datetime64[ns]

我明白了

pandas.to_datetime(df['date'], errors="coerce", unit='ms')

有没有解决方案来获得所需的输出

0   2019-07-02 08:06:39.651
1                       NaT
2                       NaT
Name: date, dtype: datetime64[ns]

名称:日期,dtype:datetime64 [ns]

1 个答案:

答案 0 :(得分:0)

您可以使用日期时间包

import datetime
s = 1236472051807 / 1000.0
datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')

我认为这可能对您有帮助